blob: 113ed98eb3cfa609c5e58c821166ee6ffd603004 [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,
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000166 Depth, Position, ParamName, Typename);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000167 if (Invalid)
168 Param->setInvalidDecl();
169
170 if (ParamName) {
171 // Add the template parameter into the current scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000172 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor72c3f312008-12-05 18:15:24 +0000173 IdResolver.AddDecl(Param);
174 }
175
Chris Lattnerb28317a2009-03-28 19:18:32 +0000176 return DeclPtrTy::make(Param);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000177}
178
Douglas Gregord684b002009-02-10 19:49:53 +0000179/// ActOnTypeParameterDefault - Adds a default argument (the type
180/// Default) to the given template type parameter (TypeParam).
Chris Lattnerb28317a2009-03-28 19:18:32 +0000181void Sema::ActOnTypeParameterDefault(DeclPtrTy TypeParam,
Douglas Gregord684b002009-02-10 19:49:53 +0000182 SourceLocation EqualLoc,
183 SourceLocation DefaultLoc,
184 TypeTy *DefaultT) {
185 TemplateTypeParmDecl *Parm
Chris Lattnerb28317a2009-03-28 19:18:32 +0000186 = cast<TemplateTypeParmDecl>(TypeParam.getAs<Decl>());
Douglas Gregord684b002009-02-10 19:49:53 +0000187 QualType Default = QualType::getFromOpaquePtr(DefaultT);
188
189 // C++ [temp.param]p14:
190 // A template-parameter shall not be used in its own default argument.
191 // FIXME: Implement this check! Needs a recursive walk over the types.
192
193 // Check the template argument itself.
194 if (CheckTemplateArgument(Parm, Default, DefaultLoc)) {
195 Parm->setInvalidDecl();
196 return;
197 }
198
199 Parm->setDefaultArgument(Default, DefaultLoc, false);
200}
201
Douglas Gregor2943aed2009-03-03 04:44:36 +0000202/// \brief Check that the type of a non-type template parameter is
203/// well-formed.
204///
205/// \returns the (possibly-promoted) parameter type if valid;
206/// otherwise, produces a diagnostic and returns a NULL type.
207QualType
208Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
209 // C++ [temp.param]p4:
210 //
211 // A non-type template-parameter shall have one of the following
212 // (optionally cv-qualified) types:
213 //
214 // -- integral or enumeration type,
215 if (T->isIntegralType() || T->isEnumeralType() ||
216 // -- pointer to object or pointer to function,
217 (T->isPointerType() &&
218 (T->getAsPointerType()->getPointeeType()->isObjectType() ||
219 T->getAsPointerType()->getPointeeType()->isFunctionType())) ||
220 // -- reference to object or reference to function,
221 T->isReferenceType() ||
222 // -- pointer to member.
223 T->isMemberPointerType() ||
224 // If T is a dependent type, we can't do the check now, so we
225 // assume that it is well-formed.
226 T->isDependentType())
227 return T;
228 // C++ [temp.param]p8:
229 //
230 // A non-type template-parameter of type "array of T" or
231 // "function returning T" is adjusted to be of type "pointer to
232 // T" or "pointer to function returning T", respectively.
233 else if (T->isArrayType())
234 // FIXME: Keep the type prior to promotion?
235 return Context.getArrayDecayedType(T);
236 else if (T->isFunctionType())
237 // FIXME: Keep the type prior to promotion?
238 return Context.getPointerType(T);
239
240 Diag(Loc, diag::err_template_nontype_parm_bad_type)
241 << T;
242
243 return QualType();
244}
245
Douglas Gregor72c3f312008-12-05 18:15:24 +0000246/// ActOnNonTypeTemplateParameter - Called when a C++ non-type
247/// template parameter (e.g., "int Size" in "template<int Size>
248/// class Array") has been parsed. S is the current scope and D is
249/// the parsed declarator.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000250Sema::DeclPtrTy Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
251 unsigned Depth,
252 unsigned Position) {
Douglas Gregor72c3f312008-12-05 18:15:24 +0000253 QualType T = GetTypeForDeclarator(D, S);
254
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000255 assert(S->isTemplateParamScope() &&
256 "Non-type template parameter not in template parameter scope!");
Douglas Gregor72c3f312008-12-05 18:15:24 +0000257 bool Invalid = false;
258
259 IdentifierInfo *ParamName = D.getIdentifier();
260 if (ParamName) {
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000261 NamedDecl *PrevDecl = LookupName(S, ParamName, LookupTagName);
Douglas Gregorf57172b2008-12-08 18:40:42 +0000262 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor72c3f312008-12-05 18:15:24 +0000263 Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000264 PrevDecl);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000265 }
266
Douglas Gregor2943aed2009-03-03 04:44:36 +0000267 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
Douglas Gregorceef30c2009-03-09 16:46:39 +0000268 if (T.isNull()) {
Douglas Gregor2943aed2009-03-03 04:44:36 +0000269 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregorceef30c2009-03-09 16:46:39 +0000270 Invalid = true;
271 }
Douglas Gregor5d290d52009-02-10 17:43:50 +0000272
Douglas Gregor72c3f312008-12-05 18:15:24 +0000273 NonTypeTemplateParmDecl *Param
274 = NonTypeTemplateParmDecl::Create(Context, CurContext, D.getIdentifierLoc(),
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000275 Depth, Position, ParamName, T);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000276 if (Invalid)
277 Param->setInvalidDecl();
278
279 if (D.getIdentifier()) {
280 // Add the template parameter into the current scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000281 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor72c3f312008-12-05 18:15:24 +0000282 IdResolver.AddDecl(Param);
283 }
Chris Lattnerb28317a2009-03-28 19:18:32 +0000284 return DeclPtrTy::make(Param);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000285}
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000286
Douglas Gregord684b002009-02-10 19:49:53 +0000287/// \brief Adds a default argument to the given non-type template
288/// parameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000289void Sema::ActOnNonTypeTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregord684b002009-02-10 19:49:53 +0000290 SourceLocation EqualLoc,
291 ExprArg DefaultE) {
292 NonTypeTemplateParmDecl *TemplateParm
Chris Lattnerb28317a2009-03-28 19:18:32 +0000293 = cast<NonTypeTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregord684b002009-02-10 19:49:53 +0000294 Expr *Default = static_cast<Expr *>(DefaultE.get());
295
296 // C++ [temp.param]p14:
297 // A template-parameter shall not be used in its own default argument.
298 // FIXME: Implement this check! Needs a recursive walk over the types.
299
300 // Check the well-formedness of the default template argument.
Douglas Gregor02cbbd22009-06-11 18:10:32 +0000301 TemplateArgument Converted;
302 if (CheckTemplateArgument(TemplateParm, TemplateParm->getType(), Default,
303 Converted)) {
Douglas Gregord684b002009-02-10 19:49:53 +0000304 TemplateParm->setInvalidDecl();
305 return;
306 }
307
Anders Carlssone9146f22009-05-01 19:49:17 +0000308 TemplateParm->setDefaultArgument(DefaultE.takeAs<Expr>());
Douglas Gregord684b002009-02-10 19:49:53 +0000309}
310
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000311
312/// ActOnTemplateTemplateParameter - Called when a C++ template template
313/// parameter (e.g. T in template <template <typename> class T> class array)
314/// has been parsed. S is the current scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000315Sema::DeclPtrTy Sema::ActOnTemplateTemplateParameter(Scope* S,
316 SourceLocation TmpLoc,
317 TemplateParamsTy *Params,
318 IdentifierInfo *Name,
319 SourceLocation NameLoc,
320 unsigned Depth,
321 unsigned Position)
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000322{
323 assert(S->isTemplateParamScope() &&
324 "Template template parameter not in template parameter scope!");
325
326 // Construct the parameter object.
327 TemplateTemplateParmDecl *Param =
328 TemplateTemplateParmDecl::Create(Context, CurContext, TmpLoc, Depth,
329 Position, Name,
330 (TemplateParameterList*)Params);
331
332 // Make sure the parameter is valid.
333 // FIXME: Decl object is not currently invalidated anywhere so this doesn't
334 // do anything yet. However, if the template parameter list or (eventual)
335 // default value is ever invalidated, that will propagate here.
336 bool Invalid = false;
337 if (Invalid) {
338 Param->setInvalidDecl();
339 }
340
341 // If the tt-param has a name, then link the identifier into the scope
342 // and lookup mechanisms.
343 if (Name) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000344 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000345 IdResolver.AddDecl(Param);
346 }
347
Chris Lattnerb28317a2009-03-28 19:18:32 +0000348 return DeclPtrTy::make(Param);
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000349}
350
Douglas Gregord684b002009-02-10 19:49:53 +0000351/// \brief Adds a default argument to the given template template
352/// parameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000353void Sema::ActOnTemplateTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregord684b002009-02-10 19:49:53 +0000354 SourceLocation EqualLoc,
355 ExprArg DefaultE) {
356 TemplateTemplateParmDecl *TemplateParm
Chris Lattnerb28317a2009-03-28 19:18:32 +0000357 = cast<TemplateTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregord684b002009-02-10 19:49:53 +0000358
359 // Since a template-template parameter's default argument is an
360 // id-expression, it must be a DeclRefExpr.
361 DeclRefExpr *Default
362 = cast<DeclRefExpr>(static_cast<Expr *>(DefaultE.get()));
363
364 // C++ [temp.param]p14:
365 // A template-parameter shall not be used in its own default argument.
366 // FIXME: Implement this check! Needs a recursive walk over the types.
367
368 // Check the well-formedness of the template argument.
369 if (!isa<TemplateDecl>(Default->getDecl())) {
370 Diag(Default->getSourceRange().getBegin(),
371 diag::err_template_arg_must_be_template)
372 << Default->getSourceRange();
373 TemplateParm->setInvalidDecl();
374 return;
375 }
376 if (CheckTemplateArgument(TemplateParm, Default)) {
377 TemplateParm->setInvalidDecl();
378 return;
379 }
380
381 DefaultE.release();
382 TemplateParm->setDefaultArgument(Default);
383}
384
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000385/// ActOnTemplateParameterList - Builds a TemplateParameterList that
386/// contains the template parameters in Params/NumParams.
387Sema::TemplateParamsTy *
388Sema::ActOnTemplateParameterList(unsigned Depth,
389 SourceLocation ExportLoc,
390 SourceLocation TemplateLoc,
391 SourceLocation LAngleLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +0000392 DeclPtrTy *Params, unsigned NumParams,
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000393 SourceLocation RAngleLoc) {
394 if (ExportLoc.isValid())
395 Diag(ExportLoc, diag::note_template_export_unsupported);
396
Douglas Gregorddc29e12009-02-06 22:42:48 +0000397 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
398 (Decl**)Params, NumParams, RAngleLoc);
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000399}
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000400
Douglas Gregor212e81c2009-03-25 00:13:59 +0000401Sema::DeclResult
Douglas Gregorddc29e12009-02-06 22:42:48 +0000402Sema::ActOnClassTemplate(Scope *S, unsigned TagSpec, TagKind TK,
403 SourceLocation KWLoc, const CXXScopeSpec &SS,
404 IdentifierInfo *Name, SourceLocation NameLoc,
405 AttributeList *Attr,
Anders Carlsson5aeccdb2009-03-26 00:52:18 +0000406 MultiTemplateParamsArg TemplateParameterLists,
407 AccessSpecifier AS) {
Douglas Gregorddc29e12009-02-06 22:42:48 +0000408 assert(TemplateParameterLists.size() > 0 && "No template parameter lists?");
409 assert(TK != TK_Reference && "Can only declare or define class templates");
Douglas Gregord684b002009-02-10 19:49:53 +0000410 bool Invalid = false;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000411
412 // Check that we can declare a template here.
413 if (CheckTemplateDeclScope(S, TemplateParameterLists))
Douglas Gregor212e81c2009-03-25 00:13:59 +0000414 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000415
416 TagDecl::TagKind Kind;
417 switch (TagSpec) {
418 default: assert(0 && "Unknown tag type!");
419 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
420 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
421 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
422 }
423
424 // There is no such thing as an unnamed class template.
425 if (!Name) {
426 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregor212e81c2009-03-25 00:13:59 +0000427 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000428 }
429
430 // Find any previous declaration with this name.
431 LookupResult Previous = LookupParsedName(S, &SS, Name, LookupOrdinaryName,
432 true);
433 assert(!Previous.isAmbiguous() && "Ambiguity in class template redecl?");
434 NamedDecl *PrevDecl = 0;
435 if (Previous.begin() != Previous.end())
436 PrevDecl = *Previous.begin();
437
438 DeclContext *SemanticContext = CurContext;
439 if (SS.isNotEmpty() && !SS.isInvalid()) {
Douglas Gregore4e5b052009-03-19 00:18:19 +0000440 SemanticContext = computeDeclContext(SS);
Douglas Gregorddc29e12009-02-06 22:42:48 +0000441
Mike Stump390b4cc2009-05-16 07:39:55 +0000442 // FIXME: need to match up several levels of template parameter lists here.
Douglas Gregorddc29e12009-02-06 22:42:48 +0000443 }
444
445 // FIXME: member templates!
446 TemplateParameterList *TemplateParams
447 = static_cast<TemplateParameterList *>(*TemplateParameterLists.release());
448
449 // If there is a previous declaration with the same name, check
450 // whether this is a valid redeclaration.
451 ClassTemplateDecl *PrevClassTemplate
452 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
453 if (PrevClassTemplate) {
454 // Ensure that the template parameter lists are compatible.
455 if (!TemplateParameterListsAreEqual(TemplateParams,
456 PrevClassTemplate->getTemplateParameters(),
457 /*Complain=*/true))
Douglas Gregor212e81c2009-03-25 00:13:59 +0000458 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000459
460 // C++ [temp.class]p4:
461 // In a redeclaration, partial specialization, explicit
462 // specialization or explicit instantiation of a class template,
463 // the class-key shall agree in kind with the original class
464 // template declaration (7.1.5.3).
465 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Douglas Gregor501c5ce2009-05-14 16:41:31 +0000466 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind, KWLoc, *Name)) {
Douglas Gregora3a83512009-04-01 23:51:29 +0000467 Diag(KWLoc, diag::err_use_with_wrong_tag)
468 << Name
469 << CodeModificationHint::CreateReplacement(KWLoc,
470 PrevRecordDecl->getKindName());
Douglas Gregorddc29e12009-02-06 22:42:48 +0000471 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregora3a83512009-04-01 23:51:29 +0000472 Kind = PrevRecordDecl->getTagKind();
Douglas Gregorddc29e12009-02-06 22:42:48 +0000473 }
474
Douglas Gregorddc29e12009-02-06 22:42:48 +0000475 // Check for redefinition of this class template.
476 if (TK == TK_Definition) {
477 if (TagDecl *Def = PrevRecordDecl->getDefinition(Context)) {
478 Diag(NameLoc, diag::err_redefinition) << Name;
479 Diag(Def->getLocation(), diag::note_previous_definition);
480 // FIXME: Would it make sense to try to "forget" the previous
481 // definition, as part of error recovery?
Douglas Gregor212e81c2009-03-25 00:13:59 +0000482 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000483 }
484 }
485 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
486 // Maybe we will complain about the shadowed template parameter.
487 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
488 // Just pretend that we didn't see the previous declaration.
489 PrevDecl = 0;
490 } else if (PrevDecl) {
491 // C++ [temp]p5:
492 // A class template shall not have the same name as any other
493 // template, class, function, object, enumeration, enumerator,
494 // namespace, or type in the same scope (3.3), except as specified
495 // in (14.5.4).
496 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
497 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor212e81c2009-03-25 00:13:59 +0000498 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000499 }
500
Douglas Gregord684b002009-02-10 19:49:53 +0000501 // Check the template parameter list of this declaration, possibly
502 // merging in the template parameter list from the previous class
503 // template declaration.
504 if (CheckTemplateParameterList(TemplateParams,
505 PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0))
506 Invalid = true;
507
Douglas Gregor7da97d02009-05-10 22:57:19 +0000508 // FIXME: If we had a scope specifier, we better have a previous template
Douglas Gregorddc29e12009-02-06 22:42:48 +0000509 // declaration!
510
Douglas Gregorbefc20e2009-03-26 00:10:35 +0000511 CXXRecordDecl *NewClass =
Douglas Gregorddc29e12009-02-06 22:42:48 +0000512 CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name,
513 PrevClassTemplate?
Douglas Gregoraafc0cc2009-05-15 19:11:46 +0000514 PrevClassTemplate->getTemplatedDecl() : 0,
515 /*DelayTypeCreation=*/true);
Douglas Gregorddc29e12009-02-06 22:42:48 +0000516
517 ClassTemplateDecl *NewTemplate
518 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
519 DeclarationName(Name), TemplateParams,
Douglas Gregor5953d8b2009-03-19 17:26:29 +0000520 NewClass, PrevClassTemplate);
Douglas Gregorbefc20e2009-03-26 00:10:35 +0000521 NewClass->setDescribedClassTemplate(NewTemplate);
522
Douglas Gregoraafc0cc2009-05-15 19:11:46 +0000523 // Build the type for the class template declaration now.
524 QualType T =
525 Context.getTypeDeclType(NewClass,
526 PrevClassTemplate?
527 PrevClassTemplate->getTemplatedDecl() : 0);
528 assert(T->isDependentType() && "Class template type is not dependent?");
529 (void)T;
530
Anders Carlsson4cbe82c2009-03-26 01:24:28 +0000531 // Set the access specifier.
532 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
533
Douglas Gregorddc29e12009-02-06 22:42:48 +0000534 // Set the lexical context of these templates
535 NewClass->setLexicalDeclContext(CurContext);
536 NewTemplate->setLexicalDeclContext(CurContext);
537
538 if (TK == TK_Definition)
539 NewClass->startDefinition();
540
541 if (Attr)
542 ProcessDeclAttributeList(NewClass, Attr);
543
544 PushOnScopeChains(NewTemplate, S);
545
Douglas Gregord684b002009-02-10 19:49:53 +0000546 if (Invalid) {
547 NewTemplate->setInvalidDecl();
548 NewClass->setInvalidDecl();
549 }
Chris Lattnerb28317a2009-03-28 19:18:32 +0000550 return DeclPtrTy::make(NewTemplate);
Douglas Gregorddc29e12009-02-06 22:42:48 +0000551}
552
Douglas Gregord684b002009-02-10 19:49:53 +0000553/// \brief Checks the validity of a template parameter list, possibly
554/// considering the template parameter list from a previous
555/// declaration.
556///
557/// If an "old" template parameter list is provided, it must be
558/// equivalent (per TemplateParameterListsAreEqual) to the "new"
559/// template parameter list.
560///
561/// \param NewParams Template parameter list for a new template
562/// declaration. This template parameter list will be updated with any
563/// default arguments that are carried through from the previous
564/// template parameter list.
565///
566/// \param OldParams If provided, template parameter list from a
567/// previous declaration of the same template. Default template
568/// arguments will be merged from the old template parameter list to
569/// the new template parameter list.
570///
571/// \returns true if an error occurred, false otherwise.
572bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
573 TemplateParameterList *OldParams) {
574 bool Invalid = false;
575
576 // C++ [temp.param]p10:
577 // The set of default template-arguments available for use with a
578 // template declaration or definition is obtained by merging the
579 // default arguments from the definition (if in scope) and all
580 // declarations in scope in the same way default function
581 // arguments are (8.3.6).
582 bool SawDefaultArgument = false;
583 SourceLocation PreviousDefaultArgLoc;
Douglas Gregorc15cb382009-02-09 23:23:08 +0000584
Mike Stump1a35fde2009-02-11 23:03:27 +0000585 // Dummy initialization to avoid warnings.
Douglas Gregor1bc69132009-02-11 20:46:19 +0000586 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregord684b002009-02-10 19:49:53 +0000587 if (OldParams)
588 OldParam = OldParams->begin();
589
590 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
591 NewParamEnd = NewParams->end();
592 NewParam != NewParamEnd; ++NewParam) {
593 // Variables used to diagnose redundant default arguments
594 bool RedundantDefaultArg = false;
595 SourceLocation OldDefaultLoc;
596 SourceLocation NewDefaultLoc;
597
598 // Variables used to diagnose missing default arguments
599 bool MissingDefaultArg = false;
600
601 // Merge default arguments for template type parameters.
602 if (TemplateTypeParmDecl *NewTypeParm
603 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
604 TemplateTypeParmDecl *OldTypeParm
605 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
606
607 if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
608 NewTypeParm->hasDefaultArgument()) {
609 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
610 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
611 SawDefaultArgument = true;
612 RedundantDefaultArg = true;
613 PreviousDefaultArgLoc = NewDefaultLoc;
614 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
615 // Merge the default argument from the old declaration to the
616 // new declaration.
617 SawDefaultArgument = true;
618 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgument(),
619 OldTypeParm->getDefaultArgumentLoc(),
620 true);
621 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
622 } else if (NewTypeParm->hasDefaultArgument()) {
623 SawDefaultArgument = true;
624 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
625 } else if (SawDefaultArgument)
626 MissingDefaultArg = true;
627 }
628 // Merge default arguments for non-type template parameters
629 else if (NonTypeTemplateParmDecl *NewNonTypeParm
630 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
631 NonTypeTemplateParmDecl *OldNonTypeParm
632 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
633 if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
634 NewNonTypeParm->hasDefaultArgument()) {
635 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
636 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
637 SawDefaultArgument = true;
638 RedundantDefaultArg = true;
639 PreviousDefaultArgLoc = NewDefaultLoc;
640 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
641 // Merge the default argument from the old declaration to the
642 // new declaration.
643 SawDefaultArgument = true;
644 // FIXME: We need to create a new kind of "default argument"
645 // expression that points to a previous template template
646 // parameter.
647 NewNonTypeParm->setDefaultArgument(
648 OldNonTypeParm->getDefaultArgument());
649 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
650 } else if (NewNonTypeParm->hasDefaultArgument()) {
651 SawDefaultArgument = true;
652 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
653 } else if (SawDefaultArgument)
654 MissingDefaultArg = true;
655 }
656 // Merge default arguments for template template parameters
657 else {
658 TemplateTemplateParmDecl *NewTemplateParm
659 = cast<TemplateTemplateParmDecl>(*NewParam);
660 TemplateTemplateParmDecl *OldTemplateParm
661 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
662 if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
663 NewTemplateParm->hasDefaultArgument()) {
664 OldDefaultLoc = OldTemplateParm->getDefaultArgumentLoc();
665 NewDefaultLoc = NewTemplateParm->getDefaultArgumentLoc();
666 SawDefaultArgument = true;
667 RedundantDefaultArg = true;
668 PreviousDefaultArgLoc = NewDefaultLoc;
669 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
670 // Merge the default argument from the old declaration to the
671 // new declaration.
672 SawDefaultArgument = true;
Mike Stump390b4cc2009-05-16 07:39:55 +0000673 // FIXME: We need to create a new kind of "default argument" expression
674 // that points to a previous template template parameter.
Douglas Gregord684b002009-02-10 19:49:53 +0000675 NewTemplateParm->setDefaultArgument(
676 OldTemplateParm->getDefaultArgument());
677 PreviousDefaultArgLoc = OldTemplateParm->getDefaultArgumentLoc();
678 } else if (NewTemplateParm->hasDefaultArgument()) {
679 SawDefaultArgument = true;
680 PreviousDefaultArgLoc = NewTemplateParm->getDefaultArgumentLoc();
681 } else if (SawDefaultArgument)
682 MissingDefaultArg = true;
683 }
684
685 if (RedundantDefaultArg) {
686 // C++ [temp.param]p12:
687 // A template-parameter shall not be given default arguments
688 // by two different declarations in the same scope.
689 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
690 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
691 Invalid = true;
692 } else if (MissingDefaultArg) {
693 // C++ [temp.param]p11:
694 // If a template-parameter has a default template-argument,
695 // all subsequent template-parameters shall have a default
696 // template-argument supplied.
697 Diag((*NewParam)->getLocation(),
698 diag::err_template_param_default_arg_missing);
699 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
700 Invalid = true;
701 }
702
703 // If we have an old template parameter list that we're merging
704 // in, move on to the next parameter.
705 if (OldParams)
706 ++OldParam;
707 }
708
709 return Invalid;
710}
Douglas Gregorc15cb382009-02-09 23:23:08 +0000711
Douglas Gregor40808ce2009-03-09 23:48:35 +0000712/// \brief Translates template arguments as provided by the parser
713/// into template arguments used by semantic analysis.
714static void
715translateTemplateArguments(ASTTemplateArgsPtr &TemplateArgsIn,
716 SourceLocation *TemplateArgLocs,
717 llvm::SmallVector<TemplateArgument, 16> &TemplateArgs) {
718 TemplateArgs.reserve(TemplateArgsIn.size());
719
720 void **Args = TemplateArgsIn.getArgs();
721 bool *ArgIsType = TemplateArgsIn.getArgIsType();
722 for (unsigned Arg = 0, Last = TemplateArgsIn.size(); Arg != Last; ++Arg) {
723 TemplateArgs.push_back(
724 ArgIsType[Arg]? TemplateArgument(TemplateArgLocs[Arg],
725 QualType::getFromOpaquePtr(Args[Arg]))
726 : TemplateArgument(reinterpret_cast<Expr *>(Args[Arg])));
727 }
728}
729
Douglas Gregorc45c2322009-03-31 00:43:58 +0000730/// \brief Build a canonical version of a template argument list.
731///
732/// This function builds a canonical version of the given template
733/// argument list, where each of the template arguments has been
734/// converted into its canonical form. This routine is typically used
735/// to canonicalize a template argument list when the template name
736/// itself is dependent. When the template name refers to an actual
737/// template declaration, Sema::CheckTemplateArgumentList should be
738/// used to check and canonicalize the template arguments.
739///
740/// \param TemplateArgs The incoming template arguments.
741///
742/// \param NumTemplateArgs The number of template arguments in \p
743/// TemplateArgs.
744///
745/// \param Canonical A vector to be filled with the canonical versions
746/// of the template arguments.
747///
748/// \param Context The ASTContext in which the template arguments live.
749static void CanonicalizeTemplateArguments(const TemplateArgument *TemplateArgs,
750 unsigned NumTemplateArgs,
751 llvm::SmallVectorImpl<TemplateArgument> &Canonical,
752 ASTContext &Context) {
753 Canonical.reserve(NumTemplateArgs);
754 for (unsigned Idx = 0; Idx < NumTemplateArgs; ++Idx) {
755 switch (TemplateArgs[Idx].getKind()) {
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000756 case TemplateArgument::Null:
757 assert(false && "Should never see a NULL template argument here");
758 break;
759
Douglas Gregorc45c2322009-03-31 00:43:58 +0000760 case TemplateArgument::Expression:
761 // FIXME: Build canonical expression (!)
762 Canonical.push_back(TemplateArgs[Idx]);
763 break;
764
765 case TemplateArgument::Declaration:
Douglas Gregor7da97d02009-05-10 22:57:19 +0000766 Canonical.push_back(
767 TemplateArgument(SourceLocation(),
768 Context.getCanonicalDecl(TemplateArgs[Idx].getAsDecl())));
Douglas Gregorc45c2322009-03-31 00:43:58 +0000769 break;
770
771 case TemplateArgument::Integral:
772 Canonical.push_back(TemplateArgument(SourceLocation(),
773 *TemplateArgs[Idx].getAsIntegral(),
774 TemplateArgs[Idx].getIntegralType()));
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000775 break;
Douglas Gregorc45c2322009-03-31 00:43:58 +0000776
777 case TemplateArgument::Type: {
778 QualType CanonType
779 = Context.getCanonicalType(TemplateArgs[Idx].getAsType());
780 Canonical.push_back(TemplateArgument(SourceLocation(), CanonType));
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000781 break;
Douglas Gregorc45c2322009-03-31 00:43:58 +0000782 }
783 }
784 }
785}
786
Douglas Gregor7532dc62009-03-30 22:58:21 +0000787QualType Sema::CheckTemplateIdType(TemplateName Name,
788 SourceLocation TemplateLoc,
789 SourceLocation LAngleLoc,
790 const TemplateArgument *TemplateArgs,
791 unsigned NumTemplateArgs,
792 SourceLocation RAngleLoc) {
793 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregorc45c2322009-03-31 00:43:58 +0000794 if (!Template) {
795 // The template name does not resolve to a template, so we just
796 // build a dependent template-id type.
797
798 // Canonicalize the template arguments to build the canonical
799 // template-id type.
800 llvm::SmallVector<TemplateArgument, 16> CanonicalTemplateArgs;
801 CanonicalizeTemplateArguments(TemplateArgs, NumTemplateArgs,
802 CanonicalTemplateArgs, Context);
803
Douglas Gregor45fbaf02009-05-07 06:49:52 +0000804 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
Douglas Gregorc45c2322009-03-31 00:43:58 +0000805 QualType CanonType
Douglas Gregor45fbaf02009-05-07 06:49:52 +0000806 = Context.getTemplateSpecializationType(CanonName,
807 &CanonicalTemplateArgs[0],
Douglas Gregorc45c2322009-03-31 00:43:58 +0000808 CanonicalTemplateArgs.size());
809
810 // Build the dependent template-id type.
811 return Context.getTemplateSpecializationType(Name, TemplateArgs,
812 NumTemplateArgs, CanonType);
813 }
Douglas Gregor7532dc62009-03-30 22:58:21 +0000814
Douglas Gregor40808ce2009-03-09 23:48:35 +0000815 // Check that the template argument list is well-formed for this
816 // template.
Anders Carlsson9ba41642009-06-05 05:31:27 +0000817 TemplateArgumentListBuilder ConvertedTemplateArgs(Context);
Douglas Gregor7532dc62009-03-30 22:58:21 +0000818 if (CheckTemplateArgumentList(Template, TemplateLoc, LAngleLoc,
Douglas Gregor40808ce2009-03-09 23:48:35 +0000819 TemplateArgs, NumTemplateArgs, RAngleLoc,
820 ConvertedTemplateArgs))
821 return QualType();
822
823 assert((ConvertedTemplateArgs.size() ==
Douglas Gregor7532dc62009-03-30 22:58:21 +0000824 Template->getTemplateParameters()->size()) &&
Douglas Gregor40808ce2009-03-09 23:48:35 +0000825 "Converted template argument list is too short!");
826
827 QualType CanonType;
828
Douglas Gregor7532dc62009-03-30 22:58:21 +0000829 if (TemplateSpecializationType::anyDependentTemplateArguments(
Douglas Gregor40808ce2009-03-09 23:48:35 +0000830 TemplateArgs,
831 NumTemplateArgs)) {
832 // This class template specialization is a dependent
833 // type. Therefore, its canonical type is another class template
834 // specialization type that contains all of the converted
835 // arguments in canonical form. This ensures that, e.g., A<T> and
836 // A<T, T> have identical types when A is declared as:
837 //
838 // template<typename T, typename U = T> struct A;
Douglas Gregor25a3ef72009-05-07 06:41:52 +0000839 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
840 CanonType = Context.getTemplateSpecializationType(CanonName,
Anders Carlsson1c5976e2009-06-05 03:43:12 +0000841 ConvertedTemplateArgs.getFlatArgumentList(),
842 ConvertedTemplateArgs.flatSize());
Douglas Gregor7532dc62009-03-30 22:58:21 +0000843 } else if (ClassTemplateDecl *ClassTemplate
844 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregor40808ce2009-03-09 23:48:35 +0000845 // Find the class template specialization declaration that
846 // corresponds to these arguments.
847 llvm::FoldingSetNodeID ID;
Anders Carlsson1c5976e2009-06-05 03:43:12 +0000848 ClassTemplateSpecializationDecl::Profile(ID,
849 ConvertedTemplateArgs.getFlatArgumentList(),
850 ConvertedTemplateArgs.flatSize());
Douglas Gregor40808ce2009-03-09 23:48:35 +0000851 void *InsertPos = 0;
852 ClassTemplateSpecializationDecl *Decl
853 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
854 if (!Decl) {
855 // This is the first time we have referenced this class template
856 // specialization. Create the canonical declaration and add it to
857 // the set of specializations.
858 Decl = ClassTemplateSpecializationDecl::Create(Context,
Anders Carlsson1c5976e2009-06-05 03:43:12 +0000859 ClassTemplate->getDeclContext(),
860 TemplateLoc,
861 ClassTemplate,
Anders Carlsson91fdf6f2009-06-05 04:06:48 +0000862 ConvertedTemplateArgs, 0);
Douglas Gregor40808ce2009-03-09 23:48:35 +0000863 ClassTemplate->getSpecializations().InsertNode(Decl, InsertPos);
864 Decl->setLexicalDeclContext(CurContext);
865 }
866
867 CanonType = Context.getTypeDeclType(Decl);
868 }
869
870 // Build the fully-sugared type for this class template
871 // specialization, which refers back to the class template
872 // specialization we created or found.
Douglas Gregor7532dc62009-03-30 22:58:21 +0000873 return Context.getTemplateSpecializationType(Name, TemplateArgs,
874 NumTemplateArgs, CanonType);
Douglas Gregor40808ce2009-03-09 23:48:35 +0000875}
876
Douglas Gregorcc636682009-02-17 23:15:12 +0000877Action::TypeResult
Douglas Gregor7532dc62009-03-30 22:58:21 +0000878Sema::ActOnTemplateIdType(TemplateTy TemplateD, SourceLocation TemplateLoc,
879 SourceLocation LAngleLoc,
880 ASTTemplateArgsPtr TemplateArgsIn,
881 SourceLocation *TemplateArgLocs,
882 SourceLocation RAngleLoc) {
883 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Douglas Gregor55f6b142009-02-09 18:46:07 +0000884
Douglas Gregor40808ce2009-03-09 23:48:35 +0000885 // Translate the parser's template argument list in our AST format.
886 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
887 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
Douglas Gregorc15cb382009-02-09 23:23:08 +0000888
Douglas Gregor7532dc62009-03-30 22:58:21 +0000889 QualType Result = CheckTemplateIdType(Template, TemplateLoc, LAngleLoc,
Jay Foadbeaaccd2009-05-21 09:52:38 +0000890 TemplateArgs.data(),
891 TemplateArgs.size(),
Douglas Gregor7532dc62009-03-30 22:58:21 +0000892 RAngleLoc);
Douglas Gregor40808ce2009-03-09 23:48:35 +0000893 TemplateArgsIn.release();
Douglas Gregor31a19b62009-04-01 21:51:26 +0000894
895 if (Result.isNull())
896 return true;
897
Douglas Gregor5908e9f2009-02-09 19:34:22 +0000898 return Result.getAsOpaquePtr();
Douglas Gregor55f6b142009-02-09 18:46:07 +0000899}
900
Douglas Gregorc45c2322009-03-31 00:43:58 +0000901/// \brief Form a dependent template name.
902///
903/// This action forms a dependent template name given the template
904/// name and its (presumably dependent) scope specifier. For
905/// example, given "MetaFun::template apply", the scope specifier \p
906/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
907/// of the "template" keyword, and "apply" is the \p Name.
908Sema::TemplateTy
909Sema::ActOnDependentTemplateName(SourceLocation TemplateKWLoc,
910 const IdentifierInfo &Name,
911 SourceLocation NameLoc,
912 const CXXScopeSpec &SS) {
913 if (!SS.isSet() || SS.isInvalid())
914 return TemplateTy();
915
916 NestedNameSpecifier *Qualifier
917 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
918
919 // FIXME: member of the current instantiation
920
921 if (!Qualifier->isDependent()) {
922 // C++0x [temp.names]p5:
923 // If a name prefixed by the keyword template is not the name of
924 // a template, the program is ill-formed. [Note: the keyword
925 // template may not be applied to non-template members of class
926 // templates. -end note ] [ Note: as is the case with the
927 // typename prefix, the template prefix is allowed in cases
928 // where it is not strictly necessary; i.e., when the
929 // nested-name-specifier or the expression on the left of the ->
930 // or . is not dependent on a template-parameter, or the use
931 // does not appear in the scope of a template. -end note]
932 //
933 // Note: C++03 was more strict here, because it banned the use of
934 // the "template" keyword prior to a template-name that was not a
935 // dependent name. C++ DR468 relaxed this requirement (the
936 // "template" keyword is now permitted). We follow the C++0x
937 // rules, even in C++03 mode, retroactively applying the DR.
938 TemplateTy Template;
939 TemplateNameKind TNK = isTemplateName(Name, 0, Template, &SS);
940 if (TNK == TNK_Non_template) {
941 Diag(NameLoc, diag::err_template_kw_refers_to_non_template)
942 << &Name;
943 return TemplateTy();
944 }
945
946 return Template;
947 }
948
949 return TemplateTy::make(Context.getDependentTemplateName(Qualifier, &Name));
950}
951
Douglas Gregorc15cb382009-02-09 23:23:08 +0000952/// \brief Check that the given template argument list is well-formed
953/// for specializing the given template.
954bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
955 SourceLocation TemplateLoc,
956 SourceLocation LAngleLoc,
Douglas Gregor40808ce2009-03-09 23:48:35 +0000957 const TemplateArgument *TemplateArgs,
958 unsigned NumTemplateArgs,
Douglas Gregor3e00bad2009-02-17 01:05:43 +0000959 SourceLocation RAngleLoc,
Anders Carlsson1c5976e2009-06-05 03:43:12 +0000960 TemplateArgumentListBuilder &Converted) {
Douglas Gregorc15cb382009-02-09 23:23:08 +0000961 TemplateParameterList *Params = Template->getTemplateParameters();
962 unsigned NumParams = Params->size();
Douglas Gregor40808ce2009-03-09 23:48:35 +0000963 unsigned NumArgs = NumTemplateArgs;
Douglas Gregorc15cb382009-02-09 23:23:08 +0000964 bool Invalid = false;
965
966 if (NumArgs > NumParams ||
Douglas Gregor62cb18d2009-02-11 18:16:40 +0000967 NumArgs < Params->getMinRequiredArguments()) {
Douglas Gregorc15cb382009-02-09 23:23:08 +0000968 // FIXME: point at either the first arg beyond what we can handle,
969 // or the '>', depending on whether we have too many or too few
970 // arguments.
971 SourceRange Range;
972 if (NumArgs > NumParams)
Douglas Gregor40808ce2009-03-09 23:48:35 +0000973 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
Douglas Gregorc15cb382009-02-09 23:23:08 +0000974 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
975 << (NumArgs > NumParams)
976 << (isa<ClassTemplateDecl>(Template)? 0 :
977 isa<FunctionTemplateDecl>(Template)? 1 :
978 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
979 << Template << Range;
Douglas Gregor62cb18d2009-02-11 18:16:40 +0000980 Diag(Template->getLocation(), diag::note_template_decl_here)
981 << Params->getSourceRange();
Douglas Gregorc15cb382009-02-09 23:23:08 +0000982 Invalid = true;
983 }
984
985 // C++ [temp.arg]p1:
986 // [...] The type and form of each template-argument specified in
987 // a template-id shall match the type and form specified for the
988 // corresponding parameter declared by the template in its
989 // template-parameter-list.
990 unsigned ArgIdx = 0;
991 for (TemplateParameterList::iterator Param = Params->begin(),
992 ParamEnd = Params->end();
993 Param != ParamEnd; ++Param, ++ArgIdx) {
994 // Decode the template argument
Douglas Gregor40808ce2009-03-09 23:48:35 +0000995 TemplateArgument Arg;
Douglas Gregorc15cb382009-02-09 23:23:08 +0000996 if (ArgIdx >= NumArgs) {
Douglas Gregor3e00bad2009-02-17 01:05:43 +0000997 // Retrieve the default template argument from the template
998 // parameter.
999 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
1000 if (!TTP->hasDefaultArgument())
1001 break;
1002
Douglas Gregor40808ce2009-03-09 23:48:35 +00001003 QualType ArgType = TTP->getDefaultArgument();
Douglas Gregor99ebf652009-02-27 19:31:52 +00001004
1005 // If the argument type is dependent, instantiate it now based
1006 // on the previously-computed template arguments.
Douglas Gregordf667e72009-03-10 20:44:00 +00001007 if (ArgType->isDependentType()) {
1008 InstantiatingTemplate Inst(*this, TemplateLoc,
Anders Carlsson1c5976e2009-06-05 03:43:12 +00001009 Template, Converted.getFlatArgumentList(),
1010 Converted.flatSize(),
Douglas Gregordf667e72009-03-10 20:44:00 +00001011 SourceRange(TemplateLoc, RAngleLoc));
Douglas Gregor7e063902009-05-11 23:53:27 +00001012
Anders Carlssone9c904b2009-06-05 04:47:51 +00001013 TemplateArgumentList TemplateArgs(Context, Converted,
1014 /*CopyArgs=*/false,
1015 /*FlattenArgs=*/false);
Douglas Gregor7e063902009-05-11 23:53:27 +00001016 ArgType = InstantiateType(ArgType, TemplateArgs,
Douglas Gregor99ebf652009-02-27 19:31:52 +00001017 TTP->getDefaultArgumentLoc(),
1018 TTP->getDeclName());
Douglas Gregordf667e72009-03-10 20:44:00 +00001019 }
Douglas Gregor99ebf652009-02-27 19:31:52 +00001020
1021 if (ArgType.isNull())
Douglas Gregorcd281c32009-02-28 00:25:32 +00001022 return true;
Douglas Gregor99ebf652009-02-27 19:31:52 +00001023
Douglas Gregor40808ce2009-03-09 23:48:35 +00001024 Arg = TemplateArgument(TTP->getLocation(), ArgType);
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001025 } else if (NonTypeTemplateParmDecl *NTTP
1026 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
1027 if (!NTTP->hasDefaultArgument())
1028 break;
1029
Anders Carlsson3b56c002009-06-11 16:06:49 +00001030 InstantiatingTemplate Inst(*this, TemplateLoc,
1031 Template, Converted.getFlatArgumentList(),
1032 Converted.flatSize(),
1033 SourceRange(TemplateLoc, RAngleLoc));
1034
1035 TemplateArgumentList TemplateArgs(Context, Converted,
1036 /*CopyArgs=*/false,
1037 /*FlattenArgs=*/false);
1038
1039 Sema::OwningExprResult E = InstantiateExpr(NTTP->getDefaultArgument(),
1040 TemplateArgs);
1041 if (E.isInvalid())
1042 return true;
1043
1044 Arg = TemplateArgument(E.takeAs<Expr>());
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001045 } else {
1046 TemplateTemplateParmDecl *TempParm
1047 = cast<TemplateTemplateParmDecl>(*Param);
1048
1049 if (!TempParm->hasDefaultArgument())
1050 break;
1051
Douglas Gregor2943aed2009-03-03 04:44:36 +00001052 // FIXME: Instantiate default argument
Douglas Gregor40808ce2009-03-09 23:48:35 +00001053 Arg = TemplateArgument(TempParm->getDefaultArgument());
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001054 }
1055 } else {
1056 // Retrieve the template argument produced by the user.
Douglas Gregor40808ce2009-03-09 23:48:35 +00001057 Arg = TemplateArgs[ArgIdx];
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001058 }
1059
Douglas Gregorc15cb382009-02-09 23:23:08 +00001060
1061 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
1062 // Check template type parameters.
Douglas Gregor40808ce2009-03-09 23:48:35 +00001063 if (Arg.getKind() == TemplateArgument::Type) {
1064 if (CheckTemplateArgument(TTP, Arg.getAsType(), Arg.getLocation()))
Douglas Gregorc15cb382009-02-09 23:23:08 +00001065 Invalid = true;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001066
1067 // Add the converted template type argument.
1068 Converted.push_back(
Douglas Gregor40808ce2009-03-09 23:48:35 +00001069 TemplateArgument(Arg.getLocation(),
1070 Context.getCanonicalType(Arg.getAsType())));
Douglas Gregorc15cb382009-02-09 23:23:08 +00001071 continue;
1072 }
1073
1074 // C++ [temp.arg.type]p1:
1075 // A template-argument for a template-parameter which is a
1076 // type shall be a type-id.
1077
1078 // We have a template type parameter but the template argument
Douglas Gregor40808ce2009-03-09 23:48:35 +00001079 // is not a type.
1080 Diag(Arg.getLocation(), diag::err_template_arg_must_be_type);
Douglas Gregor8b642592009-02-10 00:53:15 +00001081 Diag((*Param)->getLocation(), diag::note_template_param_here);
Douglas Gregorc15cb382009-02-09 23:23:08 +00001082 Invalid = true;
1083 } else if (NonTypeTemplateParmDecl *NTTP
1084 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
1085 // Check non-type template parameters.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001086
1087 // Instantiate the type of the non-type template parameter with
1088 // the template arguments we've seen thus far.
1089 QualType NTTPType = NTTP->getType();
1090 if (NTTPType->isDependentType()) {
1091 // Instantiate the type of the non-type template parameter.
Douglas Gregordf667e72009-03-10 20:44:00 +00001092 InstantiatingTemplate Inst(*this, TemplateLoc,
Anders Carlsson1c5976e2009-06-05 03:43:12 +00001093 Template, Converted.getFlatArgumentList(),
1094 Converted.flatSize(),
Douglas Gregordf667e72009-03-10 20:44:00 +00001095 SourceRange(TemplateLoc, RAngleLoc));
1096
Anders Carlssone9c904b2009-06-05 04:47:51 +00001097 TemplateArgumentList TemplateArgs(Context, Converted,
1098 /*CopyArgs=*/false,
1099 /*FlattenArgs=*/false);
Douglas Gregor7e063902009-05-11 23:53:27 +00001100 NTTPType = InstantiateType(NTTPType, TemplateArgs,
Douglas Gregor2943aed2009-03-03 04:44:36 +00001101 NTTP->getLocation(),
1102 NTTP->getDeclName());
1103 // If that worked, check the non-type template parameter type
1104 // for validity.
1105 if (!NTTPType.isNull())
1106 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
1107 NTTP->getLocation());
1108
1109 if (NTTPType.isNull()) {
1110 Invalid = true;
1111 break;
1112 }
1113 }
1114
Douglas Gregor40808ce2009-03-09 23:48:35 +00001115 switch (Arg.getKind()) {
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001116 case TemplateArgument::Null:
1117 assert(false && "Should never see a NULL template argument here");
1118 break;
1119
Douglas Gregor40808ce2009-03-09 23:48:35 +00001120 case TemplateArgument::Expression: {
1121 Expr *E = Arg.getAsExpr();
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001122 TemplateArgument Result;
1123 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
Douglas Gregorc15cb382009-02-09 23:23:08 +00001124 Invalid = true;
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001125 else
1126 Converted.push_back(Result);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001127 break;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001128 }
1129
Douglas Gregor40808ce2009-03-09 23:48:35 +00001130 case TemplateArgument::Declaration:
1131 case TemplateArgument::Integral:
1132 // We've already checked this template argument, so just copy
1133 // it to the list of converted arguments.
1134 Converted.push_back(Arg);
1135 break;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001136
Douglas Gregor40808ce2009-03-09 23:48:35 +00001137 case TemplateArgument::Type:
1138 // We have a non-type template parameter but the template
1139 // argument is a type.
1140
1141 // C++ [temp.arg]p2:
1142 // In a template-argument, an ambiguity between a type-id and
1143 // an expression is resolved to a type-id, regardless of the
1144 // form of the corresponding template-parameter.
1145 //
1146 // We warn specifically about this case, since it can be rather
1147 // confusing for users.
1148 if (Arg.getAsType()->isFunctionType())
1149 Diag(Arg.getLocation(), diag::err_template_arg_nontype_ambig)
1150 << Arg.getAsType();
1151 else
1152 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr);
1153 Diag((*Param)->getLocation(), diag::note_template_param_here);
1154 Invalid = true;
1155 }
Douglas Gregorc15cb382009-02-09 23:23:08 +00001156 } else {
1157 // Check template template parameters.
1158 TemplateTemplateParmDecl *TempParm
1159 = cast<TemplateTemplateParmDecl>(*Param);
1160
Douglas Gregor40808ce2009-03-09 23:48:35 +00001161 switch (Arg.getKind()) {
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001162 case TemplateArgument::Null:
1163 assert(false && "Should never see a NULL template argument here");
1164 break;
1165
Douglas Gregor40808ce2009-03-09 23:48:35 +00001166 case TemplateArgument::Expression: {
1167 Expr *ArgExpr = Arg.getAsExpr();
1168 if (ArgExpr && isa<DeclRefExpr>(ArgExpr) &&
1169 isa<TemplateDecl>(cast<DeclRefExpr>(ArgExpr)->getDecl())) {
1170 if (CheckTemplateArgument(TempParm, cast<DeclRefExpr>(ArgExpr)))
1171 Invalid = true;
1172
1173 // Add the converted template argument.
Douglas Gregor7da97d02009-05-10 22:57:19 +00001174 Decl *D
1175 = Context.getCanonicalDecl(cast<DeclRefExpr>(ArgExpr)->getDecl());
1176 Converted.push_back(TemplateArgument(Arg.getLocation(), D));
Douglas Gregor40808ce2009-03-09 23:48:35 +00001177 continue;
1178 }
1179 }
1180 // fall through
1181
1182 case TemplateArgument::Type: {
1183 // We have a template template parameter but the template
1184 // argument does not refer to a template.
1185 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
1186 Invalid = true;
1187 break;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001188 }
1189
Douglas Gregor40808ce2009-03-09 23:48:35 +00001190 case TemplateArgument::Declaration:
1191 // We've already checked this template argument, so just copy
1192 // it to the list of converted arguments.
1193 Converted.push_back(Arg);
1194 break;
1195
1196 case TemplateArgument::Integral:
1197 assert(false && "Integral argument with template template parameter");
1198 break;
1199 }
Douglas Gregorc15cb382009-02-09 23:23:08 +00001200 }
1201 }
1202
1203 return Invalid;
1204}
1205
1206/// \brief Check a template argument against its corresponding
1207/// template type parameter.
1208///
1209/// This routine implements the semantics of C++ [temp.arg.type]. It
1210/// returns true if an error occurred, and false otherwise.
1211bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
1212 QualType Arg, SourceLocation ArgLoc) {
1213 // C++ [temp.arg.type]p2:
1214 // A local type, a type with no linkage, an unnamed type or a type
1215 // compounded from any of these types shall not be used as a
1216 // template-argument for a template type-parameter.
1217 //
1218 // FIXME: Perform the recursive and no-linkage type checks.
1219 const TagType *Tag = 0;
1220 if (const EnumType *EnumT = Arg->getAsEnumType())
1221 Tag = EnumT;
1222 else if (const RecordType *RecordT = Arg->getAsRecordType())
1223 Tag = RecordT;
1224 if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod())
1225 return Diag(ArgLoc, diag::err_template_arg_local_type)
1226 << QualType(Tag, 0);
Douglas Gregor98137532009-03-10 18:33:27 +00001227 else if (Tag && !Tag->getDecl()->getDeclName() &&
1228 !Tag->getDecl()->getTypedefForAnonDecl()) {
Douglas Gregorc15cb382009-02-09 23:23:08 +00001229 Diag(ArgLoc, diag::err_template_arg_unnamed_type);
1230 Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here);
1231 return true;
1232 }
1233
1234 return false;
1235}
1236
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001237/// \brief Checks whether the given template argument is the address
1238/// of an object or function according to C++ [temp.arg.nontype]p1.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001239bool Sema::CheckTemplateArgumentAddressOfObjectOrFunction(Expr *Arg,
1240 NamedDecl *&Entity) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001241 bool Invalid = false;
1242
1243 // See through any implicit casts we added to fix the type.
1244 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
1245 Arg = Cast->getSubExpr();
1246
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001247 // C++0x allows nullptr, and there's no further checking to be done for that.
1248 if (Arg->getType()->isNullPtrType())
1249 return false;
1250
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001251 // C++ [temp.arg.nontype]p1:
1252 //
1253 // A template-argument for a non-type, non-template
1254 // template-parameter shall be one of: [...]
1255 //
1256 // -- the address of an object or function with external
1257 // linkage, including function templates and function
1258 // template-ids but excluding non-static class members,
1259 // expressed as & id-expression where the & is optional if
1260 // the name refers to a function or array, or if the
1261 // corresponding template-parameter is a reference; or
1262 DeclRefExpr *DRE = 0;
1263
1264 // Ignore (and complain about) any excess parentheses.
1265 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
1266 if (!Invalid) {
1267 Diag(Arg->getSourceRange().getBegin(),
1268 diag::err_template_arg_extra_parens)
1269 << Arg->getSourceRange();
1270 Invalid = true;
1271 }
1272
1273 Arg = Parens->getSubExpr();
1274 }
1275
1276 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
1277 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
1278 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
1279 } else
1280 DRE = dyn_cast<DeclRefExpr>(Arg);
1281
1282 if (!DRE || !isa<ValueDecl>(DRE->getDecl()))
1283 return Diag(Arg->getSourceRange().getBegin(),
1284 diag::err_template_arg_not_object_or_func_form)
1285 << Arg->getSourceRange();
1286
1287 // Cannot refer to non-static data members
1288 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl()))
1289 return Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
1290 << Field << Arg->getSourceRange();
1291
1292 // Cannot refer to non-static member functions
1293 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
1294 if (!Method->isStatic())
1295 return Diag(Arg->getSourceRange().getBegin(),
1296 diag::err_template_arg_method)
1297 << Method << Arg->getSourceRange();
1298
1299 // Functions must have external linkage.
1300 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
1301 if (Func->getStorageClass() == FunctionDecl::Static) {
1302 Diag(Arg->getSourceRange().getBegin(),
1303 diag::err_template_arg_function_not_extern)
1304 << Func << Arg->getSourceRange();
1305 Diag(Func->getLocation(), diag::note_template_arg_internal_object)
1306 << true;
1307 return true;
1308 }
1309
1310 // Okay: we've named a function with external linkage.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001311 Entity = Func;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001312 return Invalid;
1313 }
1314
1315 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
1316 if (!Var->hasGlobalStorage()) {
1317 Diag(Arg->getSourceRange().getBegin(),
1318 diag::err_template_arg_object_not_extern)
1319 << Var << Arg->getSourceRange();
1320 Diag(Var->getLocation(), diag::note_template_arg_internal_object)
1321 << true;
1322 return true;
1323 }
1324
1325 // Okay: we've named an object with external linkage
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001326 Entity = Var;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001327 return Invalid;
1328 }
1329
1330 // We found something else, but we don't know specifically what it is.
1331 Diag(Arg->getSourceRange().getBegin(),
1332 diag::err_template_arg_not_object_or_func)
1333 << Arg->getSourceRange();
1334 Diag(DRE->getDecl()->getLocation(),
1335 diag::note_template_arg_refers_here);
1336 return true;
1337}
1338
1339/// \brief Checks whether the given template argument is a pointer to
1340/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001341bool
1342Sema::CheckTemplateArgumentPointerToMember(Expr *Arg, NamedDecl *&Member) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001343 bool Invalid = false;
1344
1345 // See through any implicit casts we added to fix the type.
1346 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
1347 Arg = Cast->getSubExpr();
1348
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001349 // C++0x allows nullptr, and there's no further checking to be done for that.
1350 if (Arg->getType()->isNullPtrType())
1351 return false;
1352
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001353 // C++ [temp.arg.nontype]p1:
1354 //
1355 // A template-argument for a non-type, non-template
1356 // template-parameter shall be one of: [...]
1357 //
1358 // -- a pointer to member expressed as described in 5.3.1.
1359 QualifiedDeclRefExpr *DRE = 0;
1360
1361 // Ignore (and complain about) any excess parentheses.
1362 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
1363 if (!Invalid) {
1364 Diag(Arg->getSourceRange().getBegin(),
1365 diag::err_template_arg_extra_parens)
1366 << Arg->getSourceRange();
1367 Invalid = true;
1368 }
1369
1370 Arg = Parens->getSubExpr();
1371 }
1372
1373 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg))
1374 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
1375 DRE = dyn_cast<QualifiedDeclRefExpr>(UnOp->getSubExpr());
1376
1377 if (!DRE)
1378 return Diag(Arg->getSourceRange().getBegin(),
1379 diag::err_template_arg_not_pointer_to_member_form)
1380 << Arg->getSourceRange();
1381
1382 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
1383 assert((isa<FieldDecl>(DRE->getDecl()) ||
1384 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
1385 "Only non-static member pointers can make it here");
1386
1387 // Okay: this is the address of a non-static member, and therefore
1388 // a member pointer constant.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001389 Member = DRE->getDecl();
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001390 return Invalid;
1391 }
1392
1393 // We found something else, but we don't know specifically what it is.
1394 Diag(Arg->getSourceRange().getBegin(),
1395 diag::err_template_arg_not_pointer_to_member_form)
1396 << Arg->getSourceRange();
1397 Diag(DRE->getDecl()->getLocation(),
1398 diag::note_template_arg_refers_here);
1399 return true;
1400}
1401
Douglas Gregorc15cb382009-02-09 23:23:08 +00001402/// \brief Check a template argument against its corresponding
1403/// non-type template parameter.
1404///
Douglas Gregor2943aed2009-03-03 04:44:36 +00001405/// This routine implements the semantics of C++ [temp.arg.nontype].
1406/// It returns true if an error occurred, and false otherwise. \p
1407/// InstantiatedParamType is the type of the non-type template
1408/// parameter after it has been instantiated.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001409///
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001410/// If no error was detected, Converted receives the converted template argument.
Douglas Gregorc15cb382009-02-09 23:23:08 +00001411bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Douglas Gregor2943aed2009-03-03 04:44:36 +00001412 QualType InstantiatedParamType, Expr *&Arg,
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001413 TemplateArgument &Converted) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00001414 SourceLocation StartLoc = Arg->getSourceRange().getBegin();
1415
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001416 // If either the parameter has a dependent type or the argument is
1417 // type-dependent, there's nothing we can check now.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001418 // FIXME: Add template argument to Converted!
Douglas Gregor40808ce2009-03-09 23:48:35 +00001419 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
1420 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001421 Converted = TemplateArgument(Arg);
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001422 return false;
Douglas Gregor40808ce2009-03-09 23:48:35 +00001423 }
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001424
1425 // C++ [temp.arg.nontype]p5:
1426 // The following conversions are performed on each expression used
1427 // as a non-type template-argument. If a non-type
1428 // template-argument cannot be converted to the type of the
1429 // corresponding template-parameter then the program is
1430 // ill-formed.
1431 //
1432 // -- for a non-type template-parameter of integral or
1433 // enumeration type, integral promotions (4.5) and integral
1434 // conversions (4.7) are applied.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001435 QualType ParamType = InstantiatedParamType;
Douglas Gregora35284b2009-02-11 00:19:33 +00001436 QualType ArgType = Arg->getType();
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001437 if (ParamType->isIntegralType() || ParamType->isEnumeralType()) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001438 // C++ [temp.arg.nontype]p1:
1439 // A template-argument for a non-type, non-template
1440 // template-parameter shall be one of:
1441 //
1442 // -- an integral constant-expression of integral or enumeration
1443 // type; or
1444 // -- the name of a non-type template-parameter; or
1445 SourceLocation NonConstantLoc;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001446 llvm::APSInt Value;
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001447 if (!ArgType->isIntegralType() && !ArgType->isEnumeralType()) {
1448 Diag(Arg->getSourceRange().getBegin(),
1449 diag::err_template_arg_not_integral_or_enumeral)
1450 << ArgType << Arg->getSourceRange();
1451 Diag(Param->getLocation(), diag::note_template_param_here);
1452 return true;
1453 } else if (!Arg->isValueDependent() &&
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001454 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001455 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
1456 << ArgType << Arg->getSourceRange();
1457 return true;
1458 }
1459
1460 // FIXME: We need some way to more easily get the unqualified form
1461 // of the types without going all the way to the
1462 // canonical type.
1463 if (Context.getCanonicalType(ParamType).getCVRQualifiers())
1464 ParamType = Context.getCanonicalType(ParamType).getUnqualifiedType();
1465 if (Context.getCanonicalType(ArgType).getCVRQualifiers())
1466 ArgType = Context.getCanonicalType(ArgType).getUnqualifiedType();
1467
1468 // Try to convert the argument to the parameter's type.
1469 if (ParamType == ArgType) {
1470 // Okay: no conversion necessary
1471 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
1472 !ParamType->isEnumeralType()) {
1473 // This is an integral promotion or conversion.
1474 ImpCastExprToType(Arg, ParamType);
1475 } else {
1476 // We can't perform this conversion.
1477 Diag(Arg->getSourceRange().getBegin(),
1478 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00001479 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001480 Diag(Param->getLocation(), diag::note_template_param_here);
1481 return true;
1482 }
1483
Douglas Gregorf80a9d52009-03-14 00:20:21 +00001484 QualType IntegerType = Context.getCanonicalType(ParamType);
1485 if (const EnumType *Enum = IntegerType->getAsEnumType())
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001486 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregorf80a9d52009-03-14 00:20:21 +00001487
1488 if (!Arg->isValueDependent()) {
1489 // Check that an unsigned parameter does not receive a negative
1490 // value.
1491 if (IntegerType->isUnsignedIntegerType()
1492 && (Value.isSigned() && Value.isNegative())) {
1493 Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_negative)
1494 << Value.toString(10) << Param->getType()
1495 << Arg->getSourceRange();
1496 Diag(Param->getLocation(), diag::note_template_param_here);
1497 return true;
1498 }
1499
1500 // Check that we don't overflow the template parameter type.
1501 unsigned AllowedBits = Context.getTypeSize(IntegerType);
1502 if (Value.getActiveBits() > AllowedBits) {
1503 Diag(Arg->getSourceRange().getBegin(),
1504 diag::err_template_arg_too_large)
1505 << Value.toString(10) << Param->getType()
1506 << Arg->getSourceRange();
1507 Diag(Param->getLocation(), diag::note_template_param_here);
1508 return true;
1509 }
1510
1511 if (Value.getBitWidth() != AllowedBits)
1512 Value.extOrTrunc(AllowedBits);
1513 Value.setIsSigned(IntegerType->isSignedIntegerType());
1514 }
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001515
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001516 // Add the value of this argument to the list of converted
1517 // arguments. We use the bitwidth and signedness of the template
1518 // parameter.
1519 if (Arg->isValueDependent()) {
1520 // The argument is value-dependent. Create a new
1521 // TemplateArgument with the converted expression.
1522 Converted = TemplateArgument(Arg);
1523 return false;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001524 }
1525
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001526 Converted = TemplateArgument(StartLoc, Value,
1527 ParamType->isEnumeralType() ? ParamType
1528 : IntegerType);
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001529 return false;
1530 }
Douglas Gregora35284b2009-02-11 00:19:33 +00001531
Douglas Gregorb86b0572009-02-11 01:18:59 +00001532 // Handle pointer-to-function, reference-to-function, and
1533 // pointer-to-member-function all in (roughly) the same way.
1534 if (// -- For a non-type template-parameter of type pointer to
1535 // function, only the function-to-pointer conversion (4.3) is
1536 // applied. If the template-argument represents a set of
1537 // overloaded functions (or a pointer to such), the matching
1538 // function is selected from the set (13.4).
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001539 // In C++0x, any std::nullptr_t value can be converted.
Douglas Gregorb86b0572009-02-11 01:18:59 +00001540 (ParamType->isPointerType() &&
1541 ParamType->getAsPointerType()->getPointeeType()->isFunctionType()) ||
1542 // -- For a non-type template-parameter of type reference to
1543 // function, no conversions apply. If the template-argument
1544 // represents a set of overloaded functions, the matching
1545 // function is selected from the set (13.4).
1546 (ParamType->isReferenceType() &&
1547 ParamType->getAsReferenceType()->getPointeeType()->isFunctionType()) ||
1548 // -- For a non-type template-parameter of type pointer to
1549 // member function, no conversions apply. If the
1550 // template-argument represents a set of overloaded member
1551 // functions, the matching member function is selected from
1552 // the set (13.4).
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001553 // Again, C++0x allows a std::nullptr_t value.
Douglas Gregorb86b0572009-02-11 01:18:59 +00001554 (ParamType->isMemberPointerType() &&
1555 ParamType->getAsMemberPointerType()->getPointeeType()
1556 ->isFunctionType())) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001557 if (Context.hasSameUnqualifiedType(ArgType,
1558 ParamType.getNonReferenceType())) {
Douglas Gregora35284b2009-02-11 00:19:33 +00001559 // We don't have to do anything: the types already match.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001560 } else if (ArgType->isNullPtrType() && (ParamType->isPointerType() ||
1561 ParamType->isMemberPointerType())) {
1562 ArgType = ParamType;
1563 ImpCastExprToType(Arg, ParamType);
Douglas Gregorb86b0572009-02-11 01:18:59 +00001564 } else if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregora35284b2009-02-11 00:19:33 +00001565 ArgType = Context.getPointerType(ArgType);
1566 ImpCastExprToType(Arg, ArgType);
1567 } else if (FunctionDecl *Fn
1568 = ResolveAddressOfOverloadedFunction(Arg, ParamType, true)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001569 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
1570 return true;
1571
Douglas Gregora35284b2009-02-11 00:19:33 +00001572 FixOverloadedFunctionReference(Arg, Fn);
1573 ArgType = Arg->getType();
Douglas Gregorb86b0572009-02-11 01:18:59 +00001574 if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregora35284b2009-02-11 00:19:33 +00001575 ArgType = Context.getPointerType(Arg->getType());
1576 ImpCastExprToType(Arg, ArgType);
1577 }
1578 }
1579
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001580 if (!Context.hasSameUnqualifiedType(ArgType,
1581 ParamType.getNonReferenceType())) {
Douglas Gregora35284b2009-02-11 00:19:33 +00001582 // We can't perform this conversion.
1583 Diag(Arg->getSourceRange().getBegin(),
1584 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00001585 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregora35284b2009-02-11 00:19:33 +00001586 Diag(Param->getLocation(), diag::note_template_param_here);
1587 return true;
1588 }
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001589
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001590 if (ParamType->isMemberPointerType()) {
1591 NamedDecl *Member = 0;
1592 if (CheckTemplateArgumentPointerToMember(Arg, Member))
1593 return true;
1594
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001595 Member = cast_or_null<NamedDecl>(Context.getCanonicalDecl(Member));
1596 Converted = TemplateArgument(StartLoc, Member);
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001597 return false;
1598 }
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001599
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001600 NamedDecl *Entity = 0;
1601 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1602 return true;
1603
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001604 Entity = cast_or_null<NamedDecl>(Context.getCanonicalDecl(Entity));
1605 Converted = TemplateArgument(StartLoc, Entity);
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001606 return false;
Douglas Gregora35284b2009-02-11 00:19:33 +00001607 }
1608
Chris Lattnerfe90de72009-02-20 21:37:53 +00001609 if (ParamType->isPointerType()) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00001610 // -- for a non-type template-parameter of type pointer to
1611 // object, qualification conversions (4.4) and the
1612 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001613 // C++0x also allows a value of std::nullptr_t.
Douglas Gregorbad0e652009-03-24 20:32:41 +00001614 assert(ParamType->getAsPointerType()->getPointeeType()->isObjectType() &&
Douglas Gregorb86b0572009-02-11 01:18:59 +00001615 "Only object pointers allowed here");
Douglas Gregorf684e6e2009-02-11 00:44:29 +00001616
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001617 if (ArgType->isNullPtrType()) {
1618 ArgType = ParamType;
1619 ImpCastExprToType(Arg, ParamType);
1620 } else if (ArgType->isArrayType()) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00001621 ArgType = Context.getArrayDecayedType(ArgType);
1622 ImpCastExprToType(Arg, ArgType);
Douglas Gregorf684e6e2009-02-11 00:44:29 +00001623 }
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001624
Douglas Gregorb86b0572009-02-11 01:18:59 +00001625 if (IsQualificationConversion(ArgType, ParamType)) {
1626 ArgType = ParamType;
1627 ImpCastExprToType(Arg, ParamType);
1628 }
1629
Douglas Gregor8e6563b2009-02-11 18:22:40 +00001630 if (!Context.hasSameUnqualifiedType(ArgType, ParamType)) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00001631 // We can't perform this conversion.
1632 Diag(Arg->getSourceRange().getBegin(),
1633 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00001634 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregorb86b0572009-02-11 01:18:59 +00001635 Diag(Param->getLocation(), diag::note_template_param_here);
1636 return true;
1637 }
1638
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001639 NamedDecl *Entity = 0;
1640 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1641 return true;
1642
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001643 Entity = cast_or_null<NamedDecl>(Context.getCanonicalDecl(Entity));
1644 Converted = TemplateArgument(StartLoc, Entity);
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001645 return false;
Douglas Gregorf684e6e2009-02-11 00:44:29 +00001646 }
Douglas Gregorb86b0572009-02-11 01:18:59 +00001647
1648 if (const ReferenceType *ParamRefType = ParamType->getAsReferenceType()) {
1649 // -- For a non-type template-parameter of type reference to
1650 // object, no conversions apply. The type referred to by the
1651 // reference may be more cv-qualified than the (otherwise
1652 // identical) type of the template-argument. The
1653 // template-parameter is bound directly to the
1654 // template-argument, which must be an lvalue.
Douglas Gregorbad0e652009-03-24 20:32:41 +00001655 assert(ParamRefType->getPointeeType()->isObjectType() &&
Douglas Gregorb86b0572009-02-11 01:18:59 +00001656 "Only object references allowed here");
Douglas Gregorf684e6e2009-02-11 00:44:29 +00001657
Douglas Gregor8e6563b2009-02-11 18:22:40 +00001658 if (!Context.hasSameUnqualifiedType(ParamRefType->getPointeeType(), ArgType)) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00001659 Diag(Arg->getSourceRange().getBegin(),
1660 diag::err_template_arg_no_ref_bind)
Douglas Gregor2943aed2009-03-03 04:44:36 +00001661 << InstantiatedParamType << Arg->getType()
Douglas Gregorb86b0572009-02-11 01:18:59 +00001662 << Arg->getSourceRange();
1663 Diag(Param->getLocation(), diag::note_template_param_here);
1664 return true;
1665 }
1666
1667 unsigned ParamQuals
1668 = Context.getCanonicalType(ParamType).getCVRQualifiers();
1669 unsigned ArgQuals = Context.getCanonicalType(ArgType).getCVRQualifiers();
1670
1671 if ((ParamQuals | ArgQuals) != ParamQuals) {
1672 Diag(Arg->getSourceRange().getBegin(),
1673 diag::err_template_arg_ref_bind_ignores_quals)
Douglas Gregor2943aed2009-03-03 04:44:36 +00001674 << InstantiatedParamType << Arg->getType()
Douglas Gregorb86b0572009-02-11 01:18:59 +00001675 << Arg->getSourceRange();
1676 Diag(Param->getLocation(), diag::note_template_param_here);
1677 return true;
1678 }
1679
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001680 NamedDecl *Entity = 0;
1681 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1682 return true;
1683
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001684 Entity = cast<NamedDecl>(Context.getCanonicalDecl(Entity));
1685 Converted = TemplateArgument(StartLoc, Entity);
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001686 return false;
Douglas Gregorb86b0572009-02-11 01:18:59 +00001687 }
Douglas Gregor658bbb52009-02-11 16:16:59 +00001688
1689 // -- For a non-type template-parameter of type pointer to data
1690 // member, qualification conversions (4.4) are applied.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001691 // C++0x allows std::nullptr_t values.
Douglas Gregor658bbb52009-02-11 16:16:59 +00001692 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
1693
Douglas Gregor8e6563b2009-02-11 18:22:40 +00001694 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
Douglas Gregor658bbb52009-02-11 16:16:59 +00001695 // Types match exactly: nothing more to do here.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001696 } else if (ArgType->isNullPtrType()) {
1697 ImpCastExprToType(Arg, ParamType);
Douglas Gregor658bbb52009-02-11 16:16:59 +00001698 } else if (IsQualificationConversion(ArgType, ParamType)) {
1699 ImpCastExprToType(Arg, ParamType);
1700 } else {
1701 // We can't perform this conversion.
1702 Diag(Arg->getSourceRange().getBegin(),
1703 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00001704 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor658bbb52009-02-11 16:16:59 +00001705 Diag(Param->getLocation(), diag::note_template_param_here);
1706 return true;
1707 }
1708
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001709 NamedDecl *Member = 0;
1710 if (CheckTemplateArgumentPointerToMember(Arg, Member))
1711 return true;
1712
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001713 Member = cast_or_null<NamedDecl>(Context.getCanonicalDecl(Member));
1714 Converted = TemplateArgument(StartLoc, Member);
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001715 return false;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001716}
1717
1718/// \brief Check a template argument against its corresponding
1719/// template template parameter.
1720///
1721/// This routine implements the semantics of C++ [temp.arg.template].
1722/// It returns true if an error occurred, and false otherwise.
1723bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
1724 DeclRefExpr *Arg) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00001725 assert(isa<TemplateDecl>(Arg->getDecl()) && "Only template decls allowed");
1726 TemplateDecl *Template = cast<TemplateDecl>(Arg->getDecl());
1727
1728 // C++ [temp.arg.template]p1:
1729 // A template-argument for a template template-parameter shall be
1730 // the name of a class template, expressed as id-expression. Only
1731 // primary class templates are considered when matching the
1732 // template template argument with the corresponding parameter;
1733 // partial specializations are not considered even if their
1734 // parameter lists match that of the template template parameter.
Douglas Gregorba1ecb52009-06-12 19:43:02 +00001735 //
1736 // Note that we also allow template template parameters here, which
1737 // will happen when we are dealing with, e.g., class template
1738 // partial specializations.
1739 if (!isa<ClassTemplateDecl>(Template) &&
1740 !isa<TemplateTemplateParmDecl>(Template)) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00001741 assert(isa<FunctionTemplateDecl>(Template) &&
1742 "Only function templates are possible here");
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001743 Diag(Arg->getSourceRange().getBegin(),
1744 diag::note_template_arg_refers_here_func)
Douglas Gregordd0574e2009-02-10 00:24:35 +00001745 << Template;
1746 }
1747
1748 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
1749 Param->getTemplateParameters(),
1750 true, true,
1751 Arg->getSourceRange().getBegin());
Douglas Gregorc15cb382009-02-09 23:23:08 +00001752}
1753
Douglas Gregorddc29e12009-02-06 22:42:48 +00001754/// \brief Determine whether the given template parameter lists are
1755/// equivalent.
1756///
1757/// \param New The new template parameter list, typically written in the
1758/// source code as part of a new template declaration.
1759///
1760/// \param Old The old template parameter list, typically found via
1761/// name lookup of the template declared with this template parameter
1762/// list.
1763///
1764/// \param Complain If true, this routine will produce a diagnostic if
1765/// the template parameter lists are not equivalent.
1766///
Douglas Gregordd0574e2009-02-10 00:24:35 +00001767/// \param IsTemplateTemplateParm If true, this routine is being
1768/// called to compare the template parameter lists of a template
1769/// template parameter.
1770///
1771/// \param TemplateArgLoc If this source location is valid, then we
1772/// are actually checking the template parameter list of a template
1773/// argument (New) against the template parameter list of its
1774/// corresponding template template parameter (Old). We produce
1775/// slightly different diagnostics in this scenario.
1776///
Douglas Gregorddc29e12009-02-06 22:42:48 +00001777/// \returns True if the template parameter lists are equal, false
1778/// otherwise.
1779bool
1780Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
1781 TemplateParameterList *Old,
1782 bool Complain,
Douglas Gregordd0574e2009-02-10 00:24:35 +00001783 bool IsTemplateTemplateParm,
1784 SourceLocation TemplateArgLoc) {
Douglas Gregorddc29e12009-02-06 22:42:48 +00001785 if (Old->size() != New->size()) {
1786 if (Complain) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00001787 unsigned NextDiag = diag::err_template_param_list_different_arity;
1788 if (TemplateArgLoc.isValid()) {
1789 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
1790 NextDiag = diag::note_template_param_list_different_arity;
1791 }
1792 Diag(New->getTemplateLoc(), NextDiag)
1793 << (New->size() > Old->size())
1794 << IsTemplateTemplateParm
1795 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
Douglas Gregorddc29e12009-02-06 22:42:48 +00001796 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
1797 << IsTemplateTemplateParm
1798 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
1799 }
1800
1801 return false;
1802 }
1803
1804 for (TemplateParameterList::iterator OldParm = Old->begin(),
1805 OldParmEnd = Old->end(), NewParm = New->begin();
1806 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
1807 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00001808 unsigned NextDiag = diag::err_template_param_different_kind;
1809 if (TemplateArgLoc.isValid()) {
1810 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
1811 NextDiag = diag::note_template_param_different_kind;
1812 }
1813 Diag((*NewParm)->getLocation(), NextDiag)
Douglas Gregorddc29e12009-02-06 22:42:48 +00001814 << IsTemplateTemplateParm;
1815 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
1816 << IsTemplateTemplateParm;
1817 return false;
1818 }
1819
1820 if (isa<TemplateTypeParmDecl>(*OldParm)) {
1821 // Okay; all template type parameters are equivalent (since we
Douglas Gregordd0574e2009-02-10 00:24:35 +00001822 // know we're at the same index).
1823#if 0
Mike Stump390b4cc2009-05-16 07:39:55 +00001824 // FIXME: Enable this code in debug mode *after* we properly go through
1825 // and "instantiate" the template parameter lists of template template
1826 // parameters. It's only after this instantiation that (1) any dependent
1827 // types within the template parameter list of the template template
1828 // parameter can be checked, and (2) the template type parameter depths
Douglas Gregordd0574e2009-02-10 00:24:35 +00001829 // will match up.
Douglas Gregorddc29e12009-02-06 22:42:48 +00001830 QualType OldParmType
1831 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*OldParm));
1832 QualType NewParmType
1833 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*NewParm));
1834 assert(Context.getCanonicalType(OldParmType) ==
1835 Context.getCanonicalType(NewParmType) &&
1836 "type parameter mismatch?");
1837#endif
1838 } else if (NonTypeTemplateParmDecl *OldNTTP
1839 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
1840 // The types of non-type template parameters must agree.
1841 NonTypeTemplateParmDecl *NewNTTP
1842 = cast<NonTypeTemplateParmDecl>(*NewParm);
1843 if (Context.getCanonicalType(OldNTTP->getType()) !=
1844 Context.getCanonicalType(NewNTTP->getType())) {
1845 if (Complain) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00001846 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
1847 if (TemplateArgLoc.isValid()) {
1848 Diag(TemplateArgLoc,
1849 diag::err_template_arg_template_params_mismatch);
1850 NextDiag = diag::note_template_nontype_parm_different_type;
1851 }
1852 Diag(NewNTTP->getLocation(), NextDiag)
Douglas Gregorddc29e12009-02-06 22:42:48 +00001853 << NewNTTP->getType()
1854 << IsTemplateTemplateParm;
1855 Diag(OldNTTP->getLocation(),
1856 diag::note_template_nontype_parm_prev_declaration)
1857 << OldNTTP->getType();
1858 }
1859 return false;
1860 }
1861 } else {
1862 // The template parameter lists of template template
1863 // parameters must agree.
1864 // FIXME: Could we perform a faster "type" comparison here?
1865 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
1866 "Only template template parameters handled here");
1867 TemplateTemplateParmDecl *OldTTP
1868 = cast<TemplateTemplateParmDecl>(*OldParm);
1869 TemplateTemplateParmDecl *NewTTP
1870 = cast<TemplateTemplateParmDecl>(*NewParm);
1871 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
1872 OldTTP->getTemplateParameters(),
1873 Complain,
Douglas Gregordd0574e2009-02-10 00:24:35 +00001874 /*IsTemplateTemplateParm=*/true,
1875 TemplateArgLoc))
Douglas Gregorddc29e12009-02-06 22:42:48 +00001876 return false;
1877 }
1878 }
1879
1880 return true;
1881}
1882
1883/// \brief Check whether a template can be declared within this scope.
1884///
1885/// If the template declaration is valid in this scope, returns
1886/// false. Otherwise, issues a diagnostic and returns true.
1887bool
1888Sema::CheckTemplateDeclScope(Scope *S,
1889 MultiTemplateParamsArg &TemplateParameterLists) {
1890 assert(TemplateParameterLists.size() > 0 && "Not a template");
1891
1892 // Find the nearest enclosing declaration scope.
1893 while ((S->getFlags() & Scope::DeclScope) == 0 ||
1894 (S->getFlags() & Scope::TemplateParamScope) != 0)
1895 S = S->getParent();
1896
1897 TemplateParameterList *TemplateParams =
1898 static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
1899 SourceLocation TemplateLoc = TemplateParams->getTemplateLoc();
1900 SourceRange TemplateRange
1901 = SourceRange(TemplateLoc, TemplateParams->getRAngleLoc());
1902
1903 // C++ [temp]p2:
1904 // A template-declaration can appear only as a namespace scope or
1905 // class scope declaration.
1906 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
1907 while (Ctx && isa<LinkageSpecDecl>(Ctx)) {
1908 if (cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
1909 return Diag(TemplateLoc, diag::err_template_linkage)
1910 << TemplateRange;
1911
1912 Ctx = Ctx->getParent();
1913 }
1914
1915 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
1916 return false;
1917
1918 return Diag(TemplateLoc, diag::err_template_outside_namespace_or_class_scope)
1919 << TemplateRange;
1920}
Douglas Gregorcc636682009-02-17 23:15:12 +00001921
Douglas Gregorff668032009-05-13 18:28:20 +00001922/// \brief Check whether a class template specialization or explicit
1923/// instantiation in the current context is well-formed.
Douglas Gregor88b70942009-02-25 22:02:03 +00001924///
Douglas Gregorff668032009-05-13 18:28:20 +00001925/// This routine determines whether a class template specialization or
1926/// explicit instantiation can be declared in the current context
1927/// (C++ [temp.expl.spec]p2, C++0x [temp.explicit]p2) and emits
1928/// appropriate diagnostics if there was an error. It returns true if
1929// there was an error that we cannot recover from, and false otherwise.
Douglas Gregor88b70942009-02-25 22:02:03 +00001930bool
1931Sema::CheckClassTemplateSpecializationScope(ClassTemplateDecl *ClassTemplate,
1932 ClassTemplateSpecializationDecl *PrevDecl,
1933 SourceLocation TemplateNameLoc,
Douglas Gregorff668032009-05-13 18:28:20 +00001934 SourceRange ScopeSpecifierRange,
1935 bool ExplicitInstantiation) {
Douglas Gregor88b70942009-02-25 22:02:03 +00001936 // C++ [temp.expl.spec]p2:
1937 // An explicit specialization shall be declared in the namespace
1938 // of which the template is a member, or, for member templates, in
1939 // the namespace of which the enclosing class or enclosing class
1940 // template is a member. An explicit specialization of a member
1941 // function, member class or static data member of a class
1942 // template shall be declared in the namespace of which the class
1943 // template is a member. Such a declaration may also be a
1944 // definition. If the declaration is not a definition, the
1945 // specialization may be defined later in the name- space in which
1946 // the explicit specialization was declared, or in a namespace
1947 // that encloses the one in which the explicit specialization was
1948 // declared.
1949 if (CurContext->getLookupContext()->isFunctionOrMethod()) {
1950 Diag(TemplateNameLoc, diag::err_template_spec_decl_function_scope)
Douglas Gregorff668032009-05-13 18:28:20 +00001951 << ExplicitInstantiation << ClassTemplate;
Douglas Gregor88b70942009-02-25 22:02:03 +00001952 return true;
1953 }
1954
1955 DeclContext *DC = CurContext->getEnclosingNamespaceContext();
1956 DeclContext *TemplateContext
1957 = ClassTemplate->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregorff668032009-05-13 18:28:20 +00001958 if ((!PrevDecl || PrevDecl->getSpecializationKind() == TSK_Undeclared) &&
1959 !ExplicitInstantiation) {
Douglas Gregor88b70942009-02-25 22:02:03 +00001960 // There is no prior declaration of this entity, so this
1961 // specialization must be in the same context as the template
1962 // itself.
1963 if (DC != TemplateContext) {
1964 if (isa<TranslationUnitDecl>(TemplateContext))
1965 Diag(TemplateNameLoc, diag::err_template_spec_decl_out_of_scope_global)
1966 << ClassTemplate << ScopeSpecifierRange;
1967 else if (isa<NamespaceDecl>(TemplateContext))
1968 Diag(TemplateNameLoc, diag::err_template_spec_decl_out_of_scope)
1969 << ClassTemplate << cast<NamedDecl>(TemplateContext)
1970 << ScopeSpecifierRange;
1971
1972 Diag(ClassTemplate->getLocation(), diag::note_template_decl_here);
1973 }
1974
1975 return false;
1976 }
1977
1978 // We have a previous declaration of this entity. Make sure that
1979 // this redeclaration (or definition) occurs in an enclosing namespace.
1980 if (!CurContext->Encloses(TemplateContext)) {
Mike Stump390b4cc2009-05-16 07:39:55 +00001981 // FIXME: In C++98, we would like to turn these errors into warnings,
1982 // dependent on a -Wc++0x flag.
Douglas Gregorff668032009-05-13 18:28:20 +00001983 bool SuppressedDiag = false;
1984 if (isa<TranslationUnitDecl>(TemplateContext)) {
1985 if (!ExplicitInstantiation || getLangOptions().CPlusPlus0x)
1986 Diag(TemplateNameLoc, diag::err_template_spec_redecl_global_scope)
1987 << ExplicitInstantiation << ClassTemplate << ScopeSpecifierRange;
1988 else
1989 SuppressedDiag = true;
1990 } else if (isa<NamespaceDecl>(TemplateContext)) {
1991 if (!ExplicitInstantiation || getLangOptions().CPlusPlus0x)
1992 Diag(TemplateNameLoc, diag::err_template_spec_redecl_out_of_scope)
1993 << ExplicitInstantiation << ClassTemplate
1994 << cast<NamedDecl>(TemplateContext) << ScopeSpecifierRange;
1995 else
1996 SuppressedDiag = true;
1997 }
Douglas Gregor88b70942009-02-25 22:02:03 +00001998
Douglas Gregorff668032009-05-13 18:28:20 +00001999 if (!SuppressedDiag)
2000 Diag(ClassTemplate->getLocation(), diag::note_template_decl_here);
Douglas Gregor88b70942009-02-25 22:02:03 +00002001 }
2002
2003 return false;
2004}
2005
Douglas Gregore94866f2009-06-12 21:21:02 +00002006/// \brief Check the non-type template arguments of a class template
2007/// partial specialization according to C++ [temp.class.spec]p9.
2008///
2009/// \returns true if there was an error, false otherwise.
2010bool Sema::CheckClassTemplatePartialSpecializationArgs(
2011 TemplateParameterList *TemplateParams,
2012 const TemplateArgument *TemplateArgs) {
2013 // FIXME: the interface to this function will have to change to
2014 // accommodate variadic templates.
2015
2016 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
2017 NonTypeTemplateParmDecl *Param
2018 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
2019 if (!Param)
2020 continue;
2021
2022 Expr *ArgExpr = TemplateArgs[I].getAsExpr();
2023 if (!ArgExpr)
2024 continue;
2025
2026 // C++ [temp.class.spec]p8:
2027 // A non-type argument is non-specialized if it is the name of a
2028 // non-type parameter. All other non-type arguments are
2029 // specialized.
2030 //
2031 // Below, we check the two conditions that only apply to
2032 // specialized non-type arguments, so skip any non-specialized
2033 // arguments.
2034 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
2035 if (isa<NonTypeTemplateParmDecl>(DRE->getDecl()))
2036 continue;
2037
2038 // C++ [temp.class.spec]p9:
2039 // Within the argument list of a class template partial
2040 // specialization, the following restrictions apply:
2041 // -- A partially specialized non-type argument expression
2042 // shall not involve a template parameter of the partial
2043 // specialization except when the argument expression is a
2044 // simple identifier.
2045 if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
2046 Diag(ArgExpr->getLocStart(),
2047 diag::err_dependent_non_type_arg_in_partial_spec)
2048 << ArgExpr->getSourceRange();
2049 return true;
2050 }
2051
2052 // -- The type of a template parameter corresponding to a
2053 // specialized non-type argument shall not be dependent on a
2054 // parameter of the specialization.
2055 if (Param->getType()->isDependentType()) {
2056 Diag(ArgExpr->getLocStart(),
2057 diag::err_dependent_typed_non_type_arg_in_partial_spec)
2058 << Param->getType()
2059 << ArgExpr->getSourceRange();
2060 Diag(Param->getLocation(), diag::note_template_param_here);
2061 return true;
2062 }
2063 }
2064
2065 return false;
2066}
2067
Douglas Gregor212e81c2009-03-25 00:13:59 +00002068Sema::DeclResult
Douglas Gregorcc636682009-02-17 23:15:12 +00002069Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec, TagKind TK,
2070 SourceLocation KWLoc,
2071 const CXXScopeSpec &SS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00002072 TemplateTy TemplateD,
Douglas Gregorcc636682009-02-17 23:15:12 +00002073 SourceLocation TemplateNameLoc,
2074 SourceLocation LAngleLoc,
Douglas Gregor40808ce2009-03-09 23:48:35 +00002075 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregorcc636682009-02-17 23:15:12 +00002076 SourceLocation *TemplateArgLocs,
2077 SourceLocation RAngleLoc,
2078 AttributeList *Attr,
2079 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregorcc636682009-02-17 23:15:12 +00002080 // Find the class template we're specializing
Douglas Gregor7532dc62009-03-30 22:58:21 +00002081 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Douglas Gregorcc636682009-02-17 23:15:12 +00002082 ClassTemplateDecl *ClassTemplate
Douglas Gregor7532dc62009-03-30 22:58:21 +00002083 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
Douglas Gregorcc636682009-02-17 23:15:12 +00002084
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002085 bool isPartialSpecialization = false;
2086
Douglas Gregor88b70942009-02-25 22:02:03 +00002087 // Check the validity of the template headers that introduce this
2088 // template.
Douglas Gregor6bc9f7e2009-02-25 22:18:32 +00002089 // FIXME: Once we have member templates, we'll need to check
2090 // C++ [temp.expl.spec]p17-18, where we could have multiple levels of
2091 // template<> headers.
Douglas Gregor4b2d3f72009-02-26 21:00:50 +00002092 if (TemplateParameterLists.size() == 0)
2093 Diag(KWLoc, diag::err_template_spec_needs_header)
Douglas Gregorb2fb6de2009-02-27 17:53:17 +00002094 << CodeModificationHint::CreateInsertion(KWLoc, "template<> ");
Douglas Gregor4b2d3f72009-02-26 21:00:50 +00002095 else {
Douglas Gregor88b70942009-02-25 22:02:03 +00002096 TemplateParameterList *TemplateParams
2097 = static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
Chris Lattnerb28317a2009-03-28 19:18:32 +00002098 if (TemplateParameterLists.size() > 1) {
2099 Diag(TemplateParams->getTemplateLoc(),
2100 diag::err_template_spec_extra_headers);
2101 return true;
2102 }
Douglas Gregor88b70942009-02-25 22:02:03 +00002103
Douglas Gregorba1ecb52009-06-12 19:43:02 +00002104 if (TemplateParams->size() > 0) {
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002105 isPartialSpecialization = true;
Douglas Gregorba1ecb52009-06-12 19:43:02 +00002106
2107 // C++ [temp.class.spec]p10:
2108 // The template parameter list of a specialization shall not
2109 // contain default template argument values.
2110 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
2111 Decl *Param = TemplateParams->getParam(I);
2112 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
2113 if (TTP->hasDefaultArgument()) {
2114 Diag(TTP->getDefaultArgumentLoc(),
2115 diag::err_default_arg_in_partial_spec);
2116 TTP->setDefaultArgument(QualType(), SourceLocation(), false);
2117 }
2118 } else if (NonTypeTemplateParmDecl *NTTP
2119 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2120 if (Expr *DefArg = NTTP->getDefaultArgument()) {
2121 Diag(NTTP->getDefaultArgumentLoc(),
2122 diag::err_default_arg_in_partial_spec)
2123 << DefArg->getSourceRange();
2124 NTTP->setDefaultArgument(0);
2125 DefArg->Destroy(Context);
2126 }
2127 } else {
2128 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
2129 if (Expr *DefArg = TTP->getDefaultArgument()) {
2130 Diag(TTP->getDefaultArgumentLoc(),
2131 diag::err_default_arg_in_partial_spec)
2132 << DefArg->getSourceRange();
2133 TTP->setDefaultArgument(0);
2134 DefArg->Destroy(Context);
2135 }
2136 }
2137 }
2138 }
Douglas Gregor88b70942009-02-25 22:02:03 +00002139 }
2140
Douglas Gregorcc636682009-02-17 23:15:12 +00002141 // Check that the specialization uses the same tag kind as the
2142 // original template.
2143 TagDecl::TagKind Kind;
2144 switch (TagSpec) {
2145 default: assert(0 && "Unknown tag type!");
2146 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2147 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2148 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2149 }
Douglas Gregor501c5ce2009-05-14 16:41:31 +00002150 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
2151 Kind, KWLoc,
2152 *ClassTemplate->getIdentifier())) {
Douglas Gregora3a83512009-04-01 23:51:29 +00002153 Diag(KWLoc, diag::err_use_with_wrong_tag)
2154 << ClassTemplate
2155 << CodeModificationHint::CreateReplacement(KWLoc,
2156 ClassTemplate->getTemplatedDecl()->getKindName());
Douglas Gregorcc636682009-02-17 23:15:12 +00002157 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
2158 diag::note_previous_use);
2159 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
2160 }
2161
Douglas Gregor40808ce2009-03-09 23:48:35 +00002162 // Translate the parser's template argument list in our AST format.
2163 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
2164 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
2165
Douglas Gregorcc636682009-02-17 23:15:12 +00002166 // Check that the template argument list is well-formed for this
2167 // template.
Anders Carlsson9ba41642009-06-05 05:31:27 +00002168 TemplateArgumentListBuilder ConvertedTemplateArgs(Context);
Douglas Gregorcc636682009-02-17 23:15:12 +00002169 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
Douglas Gregor40808ce2009-03-09 23:48:35 +00002170 &TemplateArgs[0], TemplateArgs.size(),
2171 RAngleLoc, ConvertedTemplateArgs))
Douglas Gregor212e81c2009-03-25 00:13:59 +00002172 return true;
Douglas Gregorcc636682009-02-17 23:15:12 +00002173
2174 assert((ConvertedTemplateArgs.size() ==
2175 ClassTemplate->getTemplateParameters()->size()) &&
2176 "Converted template argument list is too short!");
2177
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002178 // Find the class template (partial) specialization declaration that
Douglas Gregorcc636682009-02-17 23:15:12 +00002179 // corresponds to these arguments.
2180 llvm::FoldingSetNodeID ID;
Douglas Gregorba1ecb52009-06-12 19:43:02 +00002181 if (isPartialSpecialization) {
Douglas Gregore94866f2009-06-12 21:21:02 +00002182 if (CheckClassTemplatePartialSpecializationArgs(
2183 ClassTemplate->getTemplateParameters(),
2184 ConvertedTemplateArgs.getFlatArgumentList()))
2185 return true;
2186
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002187 // FIXME: Template parameter list matters, too
Anders Carlsson1c5976e2009-06-05 03:43:12 +00002188 ClassTemplatePartialSpecializationDecl::Profile(ID,
2189 ConvertedTemplateArgs.getFlatArgumentList(),
2190 ConvertedTemplateArgs.flatSize());
Douglas Gregorba1ecb52009-06-12 19:43:02 +00002191 }
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002192 else
Anders Carlsson1c5976e2009-06-05 03:43:12 +00002193 ClassTemplateSpecializationDecl::Profile(ID,
2194 ConvertedTemplateArgs.getFlatArgumentList(),
2195 ConvertedTemplateArgs.flatSize());
Douglas Gregorcc636682009-02-17 23:15:12 +00002196 void *InsertPos = 0;
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002197 ClassTemplateSpecializationDecl *PrevDecl = 0;
2198
2199 if (isPartialSpecialization)
2200 PrevDecl
2201 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
2202 InsertPos);
2203 else
2204 PrevDecl
2205 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorcc636682009-02-17 23:15:12 +00002206
2207 ClassTemplateSpecializationDecl *Specialization = 0;
2208
Douglas Gregor88b70942009-02-25 22:02:03 +00002209 // Check whether we can declare a class template specialization in
2210 // the current scope.
2211 if (CheckClassTemplateSpecializationScope(ClassTemplate, PrevDecl,
2212 TemplateNameLoc,
Douglas Gregorff668032009-05-13 18:28:20 +00002213 SS.getRange(),
2214 /*ExplicitInstantiation=*/false))
Douglas Gregor212e81c2009-03-25 00:13:59 +00002215 return true;
Douglas Gregor88b70942009-02-25 22:02:03 +00002216
Douglas Gregorcc636682009-02-17 23:15:12 +00002217 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
2218 // Since the only prior class template specialization with these
2219 // arguments was referenced but not declared, reuse that
2220 // declaration node as our own, updating its source location to
2221 // reflect our new declaration.
Douglas Gregorcc636682009-02-17 23:15:12 +00002222 Specialization = PrevDecl;
Douglas Gregor6bc9f7e2009-02-25 22:18:32 +00002223 Specialization->setLocation(TemplateNameLoc);
Douglas Gregorcc636682009-02-17 23:15:12 +00002224 PrevDecl = 0;
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002225 } else if (isPartialSpecialization) {
2226 // FIXME: extra checking for partial specializations
2227
2228 // Create a new class template partial specialization declaration node.
2229 TemplateParameterList *TemplateParams
2230 = static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
2231 ClassTemplatePartialSpecializationDecl *PrevPartial
2232 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
2233 ClassTemplatePartialSpecializationDecl *Partial
2234 = ClassTemplatePartialSpecializationDecl::Create(Context,
2235 ClassTemplate->getDeclContext(),
Anders Carlsson91fdf6f2009-06-05 04:06:48 +00002236 TemplateNameLoc,
2237 TemplateParams,
2238 ClassTemplate,
2239 ConvertedTemplateArgs,
2240 PrevPartial);
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002241
2242 if (PrevPartial) {
2243 ClassTemplate->getPartialSpecializations().RemoveNode(PrevPartial);
2244 ClassTemplate->getPartialSpecializations().GetOrInsertNode(Partial);
2245 } else {
2246 ClassTemplate->getPartialSpecializations().InsertNode(Partial, InsertPos);
2247 }
2248 Specialization = Partial;
Douglas Gregorcc636682009-02-17 23:15:12 +00002249 } else {
2250 // Create a new class template specialization declaration node for
2251 // this explicit specialization.
2252 Specialization
2253 = ClassTemplateSpecializationDecl::Create(Context,
2254 ClassTemplate->getDeclContext(),
2255 TemplateNameLoc,
Anders Carlsson91fdf6f2009-06-05 04:06:48 +00002256 ClassTemplate,
2257 ConvertedTemplateArgs,
Douglas Gregorcc636682009-02-17 23:15:12 +00002258 PrevDecl);
2259
2260 if (PrevDecl) {
2261 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
2262 ClassTemplate->getSpecializations().GetOrInsertNode(Specialization);
2263 } else {
2264 ClassTemplate->getSpecializations().InsertNode(Specialization,
2265 InsertPos);
2266 }
2267 }
2268
2269 // Note that this is an explicit specialization.
2270 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
2271
2272 // Check that this isn't a redefinition of this specialization.
2273 if (TK == TK_Definition) {
2274 if (RecordDecl *Def = Specialization->getDefinition(Context)) {
Mike Stump390b4cc2009-05-16 07:39:55 +00002275 // FIXME: Should also handle explicit specialization after implicit
2276 // instantiation with a special diagnostic.
Douglas Gregorcc636682009-02-17 23:15:12 +00002277 SourceRange Range(TemplateNameLoc, RAngleLoc);
2278 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002279 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregorcc636682009-02-17 23:15:12 +00002280 Diag(Def->getLocation(), diag::note_previous_definition);
2281 Specialization->setInvalidDecl();
Douglas Gregor212e81c2009-03-25 00:13:59 +00002282 return true;
Douglas Gregorcc636682009-02-17 23:15:12 +00002283 }
2284 }
2285
Douglas Gregorfc705b82009-02-26 22:19:44 +00002286 // Build the fully-sugared type for this class template
2287 // specialization as the user wrote in the specialization
2288 // itself. This means that we'll pretty-print the type retrieved
2289 // from the specialization's declaration the way that the user
2290 // actually wrote the specialization, rather than formatting the
2291 // name based on the "canonical" representation used to store the
2292 // template arguments in the specialization.
Douglas Gregore6258932009-03-19 00:39:20 +00002293 QualType WrittenTy
Douglas Gregor7532dc62009-03-30 22:58:21 +00002294 = Context.getTemplateSpecializationType(Name,
2295 &TemplateArgs[0],
2296 TemplateArgs.size(),
Douglas Gregore6258932009-03-19 00:39:20 +00002297 Context.getTypeDeclType(Specialization));
Douglas Gregor7532dc62009-03-30 22:58:21 +00002298 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregor40808ce2009-03-09 23:48:35 +00002299 TemplateArgsIn.release();
Douglas Gregorcc636682009-02-17 23:15:12 +00002300
Douglas Gregor6bc9f7e2009-02-25 22:18:32 +00002301 // C++ [temp.expl.spec]p9:
2302 // A template explicit specialization is in the scope of the
2303 // namespace in which the template was defined.
2304 //
2305 // We actually implement this paragraph where we set the semantic
2306 // context (in the creation of the ClassTemplateSpecializationDecl),
2307 // but we also maintain the lexical context where the actual
2308 // definition occurs.
Douglas Gregorcc636682009-02-17 23:15:12 +00002309 Specialization->setLexicalDeclContext(CurContext);
2310
2311 // We may be starting the definition of this specialization.
2312 if (TK == TK_Definition)
2313 Specialization->startDefinition();
2314
2315 // Add the specialization into its lexical context, so that it can
2316 // be seen when iterating through the list of declarations in that
2317 // context. However, specializations are not found by name lookup.
Douglas Gregor6ab35242009-04-09 21:40:53 +00002318 CurContext->addDecl(Context, Specialization);
Chris Lattnerb28317a2009-03-28 19:18:32 +00002319 return DeclPtrTy::make(Specialization);
Douglas Gregorcc636682009-02-17 23:15:12 +00002320}
Douglas Gregord57959a2009-03-27 23:10:48 +00002321
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002322// Explicit instantiation of a class template specialization
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002323Sema::DeclResult
2324Sema::ActOnExplicitInstantiation(Scope *S, SourceLocation TemplateLoc,
2325 unsigned TagSpec,
2326 SourceLocation KWLoc,
2327 const CXXScopeSpec &SS,
2328 TemplateTy TemplateD,
2329 SourceLocation TemplateNameLoc,
2330 SourceLocation LAngleLoc,
2331 ASTTemplateArgsPtr TemplateArgsIn,
2332 SourceLocation *TemplateArgLocs,
2333 SourceLocation RAngleLoc,
2334 AttributeList *Attr) {
2335 // Find the class template we're specializing
2336 TemplateName Name = TemplateD.getAsVal<TemplateName>();
2337 ClassTemplateDecl *ClassTemplate
2338 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
2339
2340 // Check that the specialization uses the same tag kind as the
2341 // original template.
2342 TagDecl::TagKind Kind;
2343 switch (TagSpec) {
2344 default: assert(0 && "Unknown tag type!");
2345 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2346 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2347 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2348 }
Douglas Gregor501c5ce2009-05-14 16:41:31 +00002349 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
2350 Kind, KWLoc,
2351 *ClassTemplate->getIdentifier())) {
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002352 Diag(KWLoc, diag::err_use_with_wrong_tag)
2353 << ClassTemplate
2354 << CodeModificationHint::CreateReplacement(KWLoc,
2355 ClassTemplate->getTemplatedDecl()->getKindName());
2356 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
2357 diag::note_previous_use);
2358 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
2359 }
2360
Douglas Gregorff668032009-05-13 18:28:20 +00002361 // C++0x [temp.explicit]p2:
2362 // [...] An explicit instantiation shall appear in an enclosing
2363 // namespace of its template. [...]
2364 //
2365 // This is C++ DR 275.
2366 if (CheckClassTemplateSpecializationScope(ClassTemplate, 0,
2367 TemplateNameLoc,
2368 SS.getRange(),
2369 /*ExplicitInstantiation=*/true))
2370 return true;
2371
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002372 // Translate the parser's template argument list in our AST format.
2373 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
2374 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
2375
2376 // Check that the template argument list is well-formed for this
2377 // template.
Anders Carlsson9ba41642009-06-05 05:31:27 +00002378 TemplateArgumentListBuilder ConvertedTemplateArgs(Context);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002379 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
Anders Carlsson9bff9a92009-06-05 02:12:32 +00002380 TemplateArgs.data(), TemplateArgs.size(),
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002381 RAngleLoc, ConvertedTemplateArgs))
2382 return true;
2383
2384 assert((ConvertedTemplateArgs.size() ==
2385 ClassTemplate->getTemplateParameters()->size()) &&
2386 "Converted template argument list is too short!");
2387
2388 // Find the class template specialization declaration that
2389 // corresponds to these arguments.
2390 llvm::FoldingSetNodeID ID;
Anders Carlsson1c5976e2009-06-05 03:43:12 +00002391 ClassTemplateSpecializationDecl::Profile(ID,
2392 ConvertedTemplateArgs.getFlatArgumentList(),
2393 ConvertedTemplateArgs.flatSize());
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002394 void *InsertPos = 0;
2395 ClassTemplateSpecializationDecl *PrevDecl
2396 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
2397
2398 ClassTemplateSpecializationDecl *Specialization = 0;
2399
Douglas Gregorff668032009-05-13 18:28:20 +00002400 bool SpecializationRequiresInstantiation = true;
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002401 if (PrevDecl) {
Douglas Gregorff668032009-05-13 18:28:20 +00002402 if (PrevDecl->getSpecializationKind() == TSK_ExplicitInstantiation) {
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002403 // This particular specialization has already been declared or
2404 // instantiated. We cannot explicitly instantiate it.
Douglas Gregorff668032009-05-13 18:28:20 +00002405 Diag(TemplateNameLoc, diag::err_explicit_instantiation_duplicate)
2406 << Context.getTypeDeclType(PrevDecl);
2407 Diag(PrevDecl->getLocation(),
2408 diag::note_previous_explicit_instantiation);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002409 return DeclPtrTy::make(PrevDecl);
2410 }
2411
Douglas Gregorff668032009-05-13 18:28:20 +00002412 if (PrevDecl->getSpecializationKind() == TSK_ExplicitSpecialization) {
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002413 // C++ DR 259, C++0x [temp.explicit]p4:
Douglas Gregorff668032009-05-13 18:28:20 +00002414 // For a given set of template parameters, if an explicit
2415 // instantiation of a template appears after a declaration of
2416 // an explicit specialization for that template, the explicit
2417 // instantiation has no effect.
2418 if (!getLangOptions().CPlusPlus0x) {
2419 Diag(TemplateNameLoc,
2420 diag::ext_explicit_instantiation_after_specialization)
2421 << Context.getTypeDeclType(PrevDecl);
2422 Diag(PrevDecl->getLocation(),
2423 diag::note_previous_template_specialization);
2424 }
2425
2426 // Create a new class template specialization declaration node
2427 // for this explicit specialization. This node is only used to
2428 // record the existence of this explicit instantiation for
2429 // accurate reproduction of the source code; we don't actually
2430 // use it for anything, since it is semantically irrelevant.
2431 Specialization
2432 = ClassTemplateSpecializationDecl::Create(Context,
2433 ClassTemplate->getDeclContext(),
2434 TemplateNameLoc,
2435 ClassTemplate,
Anders Carlsson91fdf6f2009-06-05 04:06:48 +00002436 ConvertedTemplateArgs, 0);
Douglas Gregorff668032009-05-13 18:28:20 +00002437 Specialization->setLexicalDeclContext(CurContext);
2438 CurContext->addDecl(Context, Specialization);
2439 return DeclPtrTy::make(Specialization);
2440 }
2441
2442 // If we have already (implicitly) instantiated this
2443 // specialization, there is less work to do.
2444 if (PrevDecl->getSpecializationKind() == TSK_ImplicitInstantiation)
2445 SpecializationRequiresInstantiation = false;
2446
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002447 // Since the only prior class template specialization with these
2448 // arguments was referenced but not declared, reuse that
2449 // declaration node as our own, updating its source location to
2450 // reflect our new declaration.
2451 Specialization = PrevDecl;
2452 Specialization->setLocation(TemplateNameLoc);
2453 PrevDecl = 0;
2454 } else {
2455 // Create a new class template specialization declaration node for
2456 // this explicit specialization.
2457 Specialization
2458 = ClassTemplateSpecializationDecl::Create(Context,
2459 ClassTemplate->getDeclContext(),
2460 TemplateNameLoc,
2461 ClassTemplate,
Anders Carlsson91fdf6f2009-06-05 04:06:48 +00002462 ConvertedTemplateArgs, 0);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002463
2464 ClassTemplate->getSpecializations().InsertNode(Specialization,
2465 InsertPos);
2466 }
2467
2468 // Build the fully-sugared type for this explicit instantiation as
2469 // the user wrote in the explicit instantiation itself. This means
2470 // that we'll pretty-print the type retrieved from the
2471 // specialization's declaration the way that the user actually wrote
2472 // the explicit instantiation, rather than formatting the name based
2473 // on the "canonical" representation used to store the template
2474 // arguments in the specialization.
2475 QualType WrittenTy
2476 = Context.getTemplateSpecializationType(Name,
Anders Carlssonf4e2a2c2009-06-05 02:45:24 +00002477 TemplateArgs.data(),
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002478 TemplateArgs.size(),
2479 Context.getTypeDeclType(Specialization));
2480 Specialization->setTypeAsWritten(WrittenTy);
2481 TemplateArgsIn.release();
2482
2483 // Add the explicit instantiation into its lexical context. However,
2484 // since explicit instantiations are never found by name lookup, we
2485 // just put it into the declaration context directly.
2486 Specialization->setLexicalDeclContext(CurContext);
2487 CurContext->addDecl(Context, Specialization);
2488
2489 // C++ [temp.explicit]p3:
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002490 // A definition of a class template or class member template
2491 // shall be in scope at the point of the explicit instantiation of
2492 // the class template or class member template.
2493 //
2494 // This check comes when we actually try to perform the
2495 // instantiation.
Douglas Gregore2c31ff2009-05-15 17:59:04 +00002496 if (SpecializationRequiresInstantiation)
2497 InstantiateClassTemplateSpecialization(Specialization, true);
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00002498 else // Instantiate the members of this class template specialization.
Douglas Gregore2c31ff2009-05-15 17:59:04 +00002499 InstantiateClassTemplateSpecializationMembers(TemplateLoc, Specialization);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002500
2501 return DeclPtrTy::make(Specialization);
2502}
2503
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002504// Explicit instantiation of a member class of a class template.
2505Sema::DeclResult
2506Sema::ActOnExplicitInstantiation(Scope *S, SourceLocation TemplateLoc,
2507 unsigned TagSpec,
2508 SourceLocation KWLoc,
2509 const CXXScopeSpec &SS,
2510 IdentifierInfo *Name,
2511 SourceLocation NameLoc,
2512 AttributeList *Attr) {
2513
Douglas Gregor402abb52009-05-28 23:31:59 +00002514 bool Owned = false;
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002515 DeclPtrTy TagD = ActOnTag(S, TagSpec, Action::TK_Reference,
Douglas Gregor402abb52009-05-28 23:31:59 +00002516 KWLoc, SS, Name, NameLoc, Attr, AS_none, Owned);
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002517 if (!TagD)
2518 return true;
2519
2520 TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
2521 if (Tag->isEnum()) {
2522 Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
2523 << Context.getTypeDeclType(Tag);
2524 return true;
2525 }
2526
Douglas Gregord0c87372009-05-27 17:30:49 +00002527 if (Tag->isInvalidDecl())
2528 return true;
2529
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002530 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
2531 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
2532 if (!Pattern) {
2533 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
2534 << Context.getTypeDeclType(Record);
2535 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
2536 return true;
2537 }
2538
2539 // C++0x [temp.explicit]p2:
2540 // [...] An explicit instantiation shall appear in an enclosing
2541 // namespace of its template. [...]
2542 //
2543 // This is C++ DR 275.
2544 if (getLangOptions().CPlusPlus0x) {
Mike Stump390b4cc2009-05-16 07:39:55 +00002545 // FIXME: In C++98, we would like to turn these errors into warnings,
2546 // dependent on a -Wc++0x flag.
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002547 DeclContext *PatternContext
2548 = Pattern->getDeclContext()->getEnclosingNamespaceContext();
2549 if (!CurContext->Encloses(PatternContext)) {
2550 Diag(TemplateLoc, diag::err_explicit_instantiation_out_of_scope)
2551 << Record << cast<NamedDecl>(PatternContext) << SS.getRange();
2552 Diag(Pattern->getLocation(), diag::note_previous_declaration);
2553 }
2554 }
2555
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002556 if (!Record->getDefinition(Context)) {
2557 // If the class has a definition, instantiate it (and all of its
2558 // members, recursively).
2559 Pattern = cast_or_null<CXXRecordDecl>(Pattern->getDefinition(Context));
2560 if (Pattern && InstantiateClass(TemplateLoc, Record, Pattern,
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002561 getTemplateInstantiationArgs(Record),
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002562 /*ExplicitInstantiation=*/true))
2563 return true;
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00002564 } else // Instantiate all of the members of class.
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002565 InstantiateClassMembers(TemplateLoc, Record,
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002566 getTemplateInstantiationArgs(Record));
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002567
Mike Stump390b4cc2009-05-16 07:39:55 +00002568 // FIXME: We don't have any representation for explicit instantiations of
2569 // member classes. Such a representation is not needed for compilation, but it
2570 // should be available for clients that want to see all of the declarations in
2571 // the source code.
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002572 return TagD;
2573}
2574
Douglas Gregord57959a2009-03-27 23:10:48 +00002575Sema::TypeResult
2576Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
2577 const IdentifierInfo &II, SourceLocation IdLoc) {
2578 NestedNameSpecifier *NNS
2579 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
2580 if (!NNS)
2581 return true;
2582
2583 QualType T = CheckTypenameType(NNS, II, SourceRange(TypenameLoc, IdLoc));
Douglas Gregor31a19b62009-04-01 21:51:26 +00002584 if (T.isNull())
2585 return true;
Douglas Gregord57959a2009-03-27 23:10:48 +00002586 return T.getAsOpaquePtr();
2587}
2588
Douglas Gregor17343172009-04-01 00:28:59 +00002589Sema::TypeResult
2590Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
2591 SourceLocation TemplateLoc, TypeTy *Ty) {
2592 QualType T = QualType::getFromOpaquePtr(Ty);
2593 NestedNameSpecifier *NNS
2594 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
2595 const TemplateSpecializationType *TemplateId
2596 = T->getAsTemplateSpecializationType();
2597 assert(TemplateId && "Expected a template specialization type");
2598
2599 if (NNS->isDependent())
2600 return Context.getTypenameType(NNS, TemplateId).getAsOpaquePtr();
2601
2602 return Context.getQualifiedNameType(NNS, T).getAsOpaquePtr();
2603}
2604
Douglas Gregord57959a2009-03-27 23:10:48 +00002605/// \brief Build the type that describes a C++ typename specifier,
2606/// e.g., "typename T::type".
2607QualType
2608Sema::CheckTypenameType(NestedNameSpecifier *NNS, const IdentifierInfo &II,
2609 SourceRange Range) {
Douglas Gregor42af25f2009-05-11 19:58:34 +00002610 CXXRecordDecl *CurrentInstantiation = 0;
2611 if (NNS->isDependent()) {
2612 CurrentInstantiation = getCurrentInstantiationOf(NNS);
Douglas Gregord57959a2009-03-27 23:10:48 +00002613
Douglas Gregor42af25f2009-05-11 19:58:34 +00002614 // If the nested-name-specifier does not refer to the current
2615 // instantiation, then build a typename type.
2616 if (!CurrentInstantiation)
2617 return Context.getTypenameType(NNS, &II);
2618 }
Douglas Gregord57959a2009-03-27 23:10:48 +00002619
Douglas Gregor42af25f2009-05-11 19:58:34 +00002620 DeclContext *Ctx = 0;
2621
2622 if (CurrentInstantiation)
2623 Ctx = CurrentInstantiation;
2624 else {
2625 CXXScopeSpec SS;
2626 SS.setScopeRep(NNS);
2627 SS.setRange(Range);
2628 if (RequireCompleteDeclContext(SS))
2629 return QualType();
2630
2631 Ctx = computeDeclContext(SS);
2632 }
Douglas Gregord57959a2009-03-27 23:10:48 +00002633 assert(Ctx && "No declaration context?");
2634
2635 DeclarationName Name(&II);
2636 LookupResult Result = LookupQualifiedName(Ctx, Name, LookupOrdinaryName,
2637 false);
2638 unsigned DiagID = 0;
2639 Decl *Referenced = 0;
2640 switch (Result.getKind()) {
2641 case LookupResult::NotFound:
2642 if (Ctx->isTranslationUnit())
2643 DiagID = diag::err_typename_nested_not_found_global;
2644 else
2645 DiagID = diag::err_typename_nested_not_found;
2646 break;
2647
2648 case LookupResult::Found:
2649 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getAsDecl())) {
2650 // We found a type. Build a QualifiedNameType, since the
2651 // typename-specifier was just sugar. FIXME: Tell
2652 // QualifiedNameType that it has a "typename" prefix.
2653 return Context.getQualifiedNameType(NNS, Context.getTypeDeclType(Type));
2654 }
2655
2656 DiagID = diag::err_typename_nested_not_type;
2657 Referenced = Result.getAsDecl();
2658 break;
2659
2660 case LookupResult::FoundOverloaded:
2661 DiagID = diag::err_typename_nested_not_type;
2662 Referenced = *Result.begin();
2663 break;
2664
2665 case LookupResult::AmbiguousBaseSubobjectTypes:
2666 case LookupResult::AmbiguousBaseSubobjects:
2667 case LookupResult::AmbiguousReference:
2668 DiagnoseAmbiguousLookup(Result, Name, Range.getEnd(), Range);
2669 return QualType();
2670 }
2671
2672 // If we get here, it's because name lookup did not find a
2673 // type. Emit an appropriate diagnostic and return an error.
2674 if (NamedDecl *NamedCtx = dyn_cast<NamedDecl>(Ctx))
2675 Diag(Range.getEnd(), DiagID) << Range << Name << NamedCtx;
2676 else
2677 Diag(Range.getEnd(), DiagID) << Range << Name;
2678 if (Referenced)
2679 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
2680 << Name;
2681 return QualType();
2682}