blob: 55c43c2d0aa6527c364ae2a1ce4cab1f7414080e [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()) {
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +000059 Record = cast<CXXRecordDecl>(Record->getCanonicalDecl());
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 Gregorc5c903a2009-06-24 00:23:40 +000070 // FIXME: What follows is a slightly less gross hack than what used to
71 // follow.
Douglas Gregor1f27ac62009-07-29 16:15:53 +000072 if (OverloadedFunctionDecl *Ovl
73 = dyn_cast<OverloadedFunctionDecl>(IIDecl)) {
Douglas Gregord6fb7ef2008-12-18 19:37:40 +000074 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
75 FEnd = Ovl->function_end();
76 F != FEnd; ++F) {
Douglas Gregore53060f2009-06-25 22:08:12 +000077 if (isa<FunctionTemplateDecl>(*F)) {
Douglas Gregor7532dc62009-03-30 22:58:21 +000078 TemplateResult = TemplateTy::make(Ovl);
Douglas Gregor55f6b142009-02-09 18:46:07 +000079 return TNK_Function_template;
80 }
Douglas Gregord6fb7ef2008-12-18 19:37:40 +000081 }
82 }
Douglas Gregor7532dc62009-03-30 22:58:21 +000083
84 if (TNK != TNK_Non_template) {
85 if (SS && SS->isSet() && !SS->isInvalid()) {
86 NestedNameSpecifier *Qualifier
87 = static_cast<NestedNameSpecifier *>(SS->getScopeRep());
88 TemplateResult
89 = TemplateTy::make(Context.getQualifiedTemplateName(Qualifier,
90 false,
91 Template));
92 } else
93 TemplateResult = TemplateTy::make(TemplateName(Template));
94 }
Douglas Gregord6fb7ef2008-12-18 19:37:40 +000095 }
Douglas Gregor7532dc62009-03-30 22:58:21 +000096 return TNK;
Douglas Gregord6fb7ef2008-12-18 19:37:40 +000097}
98
Douglas Gregor72c3f312008-12-05 18:15:24 +000099/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
100/// that the template parameter 'PrevDecl' is being shadowed by a new
101/// declaration at location Loc. Returns true to indicate that this is
102/// an error, and false otherwise.
103bool Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
Douglas Gregorf57172b2008-12-08 18:40:42 +0000104 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregor72c3f312008-12-05 18:15:24 +0000105
106 // Microsoft Visual C++ permits template parameters to be shadowed.
107 if (getLangOptions().Microsoft)
108 return false;
109
110 // C++ [temp.local]p4:
111 // A template-parameter shall not be redeclared within its
112 // scope (including nested scopes).
113 Diag(Loc, diag::err_template_param_shadow)
114 << cast<NamedDecl>(PrevDecl)->getDeclName();
115 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
116 return true;
117}
118
Douglas Gregor2943aed2009-03-03 04:44:36 +0000119/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000120/// the parameter D to reference the templated declaration and return a pointer
121/// to the template declaration. Otherwise, do nothing to D and return null.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000122TemplateDecl *Sema::AdjustDeclIfTemplate(DeclPtrTy &D) {
123 if (TemplateDecl *Temp = dyn_cast<TemplateDecl>(D.getAs<Decl>())) {
124 D = DeclPtrTy::make(Temp->getTemplatedDecl());
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000125 return Temp;
126 }
127 return 0;
128}
129
Douglas Gregor72c3f312008-12-05 18:15:24 +0000130/// ActOnTypeParameter - Called when a C++ template type parameter
131/// (e.g., "typename T") has been parsed. Typename specifies whether
132/// the keyword "typename" was used to declare the type parameter
133/// (otherwise, "class" was used), and KeyLoc is the location of the
134/// "class" or "typename" keyword. ParamName is the name of the
135/// parameter (NULL indicates an unnamed template parameter) and
136/// ParamName is the location of the parameter name (if any).
137/// If the type parameter has a default argument, it will be added
138/// later via ActOnTypeParameterDefault.
Anders Carlsson941df7d2009-06-12 19:58:00 +0000139Sema::DeclPtrTy Sema::ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis,
140 SourceLocation EllipsisLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +0000141 SourceLocation KeyLoc,
142 IdentifierInfo *ParamName,
143 SourceLocation ParamNameLoc,
144 unsigned Depth, unsigned Position) {
Douglas Gregor72c3f312008-12-05 18:15:24 +0000145 assert(S->isTemplateParamScope() &&
146 "Template type parameter not in template parameter scope!");
147 bool Invalid = false;
148
149 if (ParamName) {
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000150 NamedDecl *PrevDecl = LookupName(S, ParamName, LookupTagName);
Douglas Gregorf57172b2008-12-08 18:40:42 +0000151 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor72c3f312008-12-05 18:15:24 +0000152 Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc,
153 PrevDecl);
154 }
155
Douglas Gregorddc29e12009-02-06 22:42:48 +0000156 SourceLocation Loc = ParamNameLoc;
157 if (!ParamName)
158 Loc = KeyLoc;
159
Douglas Gregor72c3f312008-12-05 18:15:24 +0000160 TemplateTypeParmDecl *Param
Douglas Gregorddc29e12009-02-06 22:42:48 +0000161 = TemplateTypeParmDecl::Create(Context, CurContext, Loc,
Anders Carlsson6d845ae2009-06-12 22:23:22 +0000162 Depth, Position, ParamName, Typename,
163 Ellipsis);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000164 if (Invalid)
165 Param->setInvalidDecl();
166
167 if (ParamName) {
168 // Add the template parameter into the current scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000169 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor72c3f312008-12-05 18:15:24 +0000170 IdResolver.AddDecl(Param);
171 }
172
Chris Lattnerb28317a2009-03-28 19:18:32 +0000173 return DeclPtrTy::make(Param);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000174}
175
Douglas Gregord684b002009-02-10 19:49:53 +0000176/// ActOnTypeParameterDefault - Adds a default argument (the type
177/// Default) to the given template type parameter (TypeParam).
Chris Lattnerb28317a2009-03-28 19:18:32 +0000178void Sema::ActOnTypeParameterDefault(DeclPtrTy TypeParam,
Douglas Gregord684b002009-02-10 19:49:53 +0000179 SourceLocation EqualLoc,
180 SourceLocation DefaultLoc,
181 TypeTy *DefaultT) {
182 TemplateTypeParmDecl *Parm
Chris Lattnerb28317a2009-03-28 19:18:32 +0000183 = cast<TemplateTypeParmDecl>(TypeParam.getAs<Decl>());
Douglas Gregord684b002009-02-10 19:49:53 +0000184 QualType Default = QualType::getFromOpaquePtr(DefaultT);
185
Anders Carlsson9c4c5c82009-06-12 22:30:13 +0000186 // C++0x [temp.param]p9:
187 // A default template-argument may be specified for any kind of
188 // template-parameter that is not a template parameter pack.
189 if (Parm->isParameterPack()) {
190 Diag(DefaultLoc, diag::err_template_param_pack_default_arg);
Anders Carlsson9c4c5c82009-06-12 22:30:13 +0000191 return;
192 }
193
Douglas Gregord684b002009-02-10 19:49:53 +0000194 // C++ [temp.param]p14:
195 // A template-parameter shall not be used in its own default argument.
196 // FIXME: Implement this check! Needs a recursive walk over the types.
197
198 // Check the template argument itself.
199 if (CheckTemplateArgument(Parm, Default, DefaultLoc)) {
200 Parm->setInvalidDecl();
201 return;
202 }
203
204 Parm->setDefaultArgument(Default, DefaultLoc, false);
205}
206
Douglas Gregor2943aed2009-03-03 04:44:36 +0000207/// \brief Check that the type of a non-type template parameter is
208/// well-formed.
209///
210/// \returns the (possibly-promoted) parameter type if valid;
211/// otherwise, produces a diagnostic and returns a NULL type.
212QualType
213Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
214 // C++ [temp.param]p4:
215 //
216 // A non-type template-parameter shall have one of the following
217 // (optionally cv-qualified) types:
218 //
219 // -- integral or enumeration type,
220 if (T->isIntegralType() || T->isEnumeralType() ||
221 // -- pointer to object or pointer to function,
222 (T->isPointerType() &&
Ted Kremenek35366a62009-07-17 17:50:17 +0000223 (T->getAsPointerType()->getPointeeType()->isObjectType() ||
224 T->getAsPointerType()->getPointeeType()->isFunctionType())) ||
Douglas Gregor2943aed2009-03-03 04:44:36 +0000225 // -- reference to object or reference to function,
226 T->isReferenceType() ||
227 // -- pointer to member.
228 T->isMemberPointerType() ||
229 // If T is a dependent type, we can't do the check now, so we
230 // assume that it is well-formed.
231 T->isDependentType())
232 return T;
233 // C++ [temp.param]p8:
234 //
235 // A non-type template-parameter of type "array of T" or
236 // "function returning T" is adjusted to be of type "pointer to
237 // T" or "pointer to function returning T", respectively.
238 else if (T->isArrayType())
239 // FIXME: Keep the type prior to promotion?
240 return Context.getArrayDecayedType(T);
241 else if (T->isFunctionType())
242 // FIXME: Keep the type prior to promotion?
243 return Context.getPointerType(T);
244
245 Diag(Loc, diag::err_template_nontype_parm_bad_type)
246 << T;
247
248 return QualType();
249}
250
Douglas Gregor72c3f312008-12-05 18:15:24 +0000251/// ActOnNonTypeTemplateParameter - Called when a C++ non-type
252/// template parameter (e.g., "int Size" in "template<int Size>
253/// class Array") has been parsed. S is the current scope and D is
254/// the parsed declarator.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000255Sema::DeclPtrTy Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
256 unsigned Depth,
257 unsigned Position) {
Douglas Gregor72c3f312008-12-05 18:15:24 +0000258 QualType T = GetTypeForDeclarator(D, S);
259
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000260 assert(S->isTemplateParamScope() &&
261 "Non-type template parameter not in template parameter scope!");
Douglas Gregor72c3f312008-12-05 18:15:24 +0000262 bool Invalid = false;
263
264 IdentifierInfo *ParamName = D.getIdentifier();
265 if (ParamName) {
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000266 NamedDecl *PrevDecl = LookupName(S, ParamName, LookupTagName);
Douglas Gregorf57172b2008-12-08 18:40:42 +0000267 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor72c3f312008-12-05 18:15:24 +0000268 Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000269 PrevDecl);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000270 }
271
Douglas Gregor2943aed2009-03-03 04:44:36 +0000272 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
Douglas Gregorceef30c2009-03-09 16:46:39 +0000273 if (T.isNull()) {
Douglas Gregor2943aed2009-03-03 04:44:36 +0000274 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregorceef30c2009-03-09 16:46:39 +0000275 Invalid = true;
276 }
Douglas Gregor5d290d52009-02-10 17:43:50 +0000277
Douglas Gregor72c3f312008-12-05 18:15:24 +0000278 NonTypeTemplateParmDecl *Param
279 = NonTypeTemplateParmDecl::Create(Context, CurContext, D.getIdentifierLoc(),
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000280 Depth, Position, ParamName, T);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000281 if (Invalid)
282 Param->setInvalidDecl();
283
284 if (D.getIdentifier()) {
285 // Add the template parameter into the current scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000286 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor72c3f312008-12-05 18:15:24 +0000287 IdResolver.AddDecl(Param);
288 }
Chris Lattnerb28317a2009-03-28 19:18:32 +0000289 return DeclPtrTy::make(Param);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000290}
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000291
Douglas Gregord684b002009-02-10 19:49:53 +0000292/// \brief Adds a default argument to the given non-type template
293/// parameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000294void Sema::ActOnNonTypeTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregord684b002009-02-10 19:49:53 +0000295 SourceLocation EqualLoc,
296 ExprArg DefaultE) {
297 NonTypeTemplateParmDecl *TemplateParm
Chris Lattnerb28317a2009-03-28 19:18:32 +0000298 = cast<NonTypeTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregord684b002009-02-10 19:49:53 +0000299 Expr *Default = static_cast<Expr *>(DefaultE.get());
300
301 // C++ [temp.param]p14:
302 // A template-parameter shall not be used in its own default argument.
303 // FIXME: Implement this check! Needs a recursive walk over the types.
304
305 // Check the well-formedness of the default template argument.
Douglas Gregor02cbbd22009-06-11 18:10:32 +0000306 TemplateArgument Converted;
307 if (CheckTemplateArgument(TemplateParm, TemplateParm->getType(), Default,
308 Converted)) {
Douglas Gregord684b002009-02-10 19:49:53 +0000309 TemplateParm->setInvalidDecl();
310 return;
311 }
312
Anders Carlssone9146f22009-05-01 19:49:17 +0000313 TemplateParm->setDefaultArgument(DefaultE.takeAs<Expr>());
Douglas Gregord684b002009-02-10 19:49:53 +0000314}
315
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000316
317/// ActOnTemplateTemplateParameter - Called when a C++ template template
318/// parameter (e.g. T in template <template <typename> class T> class array)
319/// has been parsed. S is the current scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000320Sema::DeclPtrTy Sema::ActOnTemplateTemplateParameter(Scope* S,
321 SourceLocation TmpLoc,
322 TemplateParamsTy *Params,
323 IdentifierInfo *Name,
324 SourceLocation NameLoc,
325 unsigned Depth,
326 unsigned Position)
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000327{
328 assert(S->isTemplateParamScope() &&
329 "Template template parameter not in template parameter scope!");
330
331 // Construct the parameter object.
332 TemplateTemplateParmDecl *Param =
333 TemplateTemplateParmDecl::Create(Context, CurContext, TmpLoc, Depth,
334 Position, Name,
335 (TemplateParameterList*)Params);
336
337 // Make sure the parameter is valid.
338 // FIXME: Decl object is not currently invalidated anywhere so this doesn't
339 // do anything yet. However, if the template parameter list or (eventual)
340 // default value is ever invalidated, that will propagate here.
341 bool Invalid = false;
342 if (Invalid) {
343 Param->setInvalidDecl();
344 }
345
346 // If the tt-param has a name, then link the identifier into the scope
347 // and lookup mechanisms.
348 if (Name) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000349 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000350 IdResolver.AddDecl(Param);
351 }
352
Chris Lattnerb28317a2009-03-28 19:18:32 +0000353 return DeclPtrTy::make(Param);
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000354}
355
Douglas Gregord684b002009-02-10 19:49:53 +0000356/// \brief Adds a default argument to the given template template
357/// parameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000358void Sema::ActOnTemplateTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregord684b002009-02-10 19:49:53 +0000359 SourceLocation EqualLoc,
360 ExprArg DefaultE) {
361 TemplateTemplateParmDecl *TemplateParm
Chris Lattnerb28317a2009-03-28 19:18:32 +0000362 = cast<TemplateTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregord684b002009-02-10 19:49:53 +0000363
364 // Since a template-template parameter's default argument is an
365 // id-expression, it must be a DeclRefExpr.
366 DeclRefExpr *Default
367 = cast<DeclRefExpr>(static_cast<Expr *>(DefaultE.get()));
368
369 // C++ [temp.param]p14:
370 // A template-parameter shall not be used in its own default argument.
371 // FIXME: Implement this check! Needs a recursive walk over the types.
372
373 // Check the well-formedness of the template argument.
374 if (!isa<TemplateDecl>(Default->getDecl())) {
375 Diag(Default->getSourceRange().getBegin(),
376 diag::err_template_arg_must_be_template)
377 << Default->getSourceRange();
378 TemplateParm->setInvalidDecl();
379 return;
380 }
381 if (CheckTemplateArgument(TemplateParm, Default)) {
382 TemplateParm->setInvalidDecl();
383 return;
384 }
385
386 DefaultE.release();
387 TemplateParm->setDefaultArgument(Default);
388}
389
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000390/// ActOnTemplateParameterList - Builds a TemplateParameterList that
391/// contains the template parameters in Params/NumParams.
392Sema::TemplateParamsTy *
393Sema::ActOnTemplateParameterList(unsigned Depth,
394 SourceLocation ExportLoc,
395 SourceLocation TemplateLoc,
396 SourceLocation LAngleLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +0000397 DeclPtrTy *Params, unsigned NumParams,
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000398 SourceLocation RAngleLoc) {
399 if (ExportLoc.isValid())
400 Diag(ExportLoc, diag::note_template_export_unsupported);
401
Douglas Gregorddc29e12009-02-06 22:42:48 +0000402 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
403 (Decl**)Params, NumParams, RAngleLoc);
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000404}
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000405
Douglas Gregor212e81c2009-03-25 00:13:59 +0000406Sema::DeclResult
Douglas Gregorbd1099e2009-07-23 16:36:45 +0000407Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagKind TK,
Douglas Gregorddc29e12009-02-06 22:42:48 +0000408 SourceLocation KWLoc, const CXXScopeSpec &SS,
409 IdentifierInfo *Name, SourceLocation NameLoc,
410 AttributeList *Attr,
Anders Carlsson5aeccdb2009-03-26 00:52:18 +0000411 MultiTemplateParamsArg TemplateParameterLists,
412 AccessSpecifier AS) {
Douglas Gregorddc29e12009-02-06 22:42:48 +0000413 assert(TemplateParameterLists.size() > 0 && "No template parameter lists?");
414 assert(TK != TK_Reference && "Can only declare or define class templates");
Douglas Gregord684b002009-02-10 19:49:53 +0000415 bool Invalid = false;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000416
417 // Check that we can declare a template here.
418 if (CheckTemplateDeclScope(S, TemplateParameterLists))
Douglas Gregor212e81c2009-03-25 00:13:59 +0000419 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000420
421 TagDecl::TagKind Kind;
422 switch (TagSpec) {
423 default: assert(0 && "Unknown tag type!");
424 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
425 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
426 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
427 }
428
429 // There is no such thing as an unnamed class template.
430 if (!Name) {
431 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregor212e81c2009-03-25 00:13:59 +0000432 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000433 }
434
435 // Find any previous declaration with this name.
436 LookupResult Previous = LookupParsedName(S, &SS, Name, LookupOrdinaryName,
437 true);
438 assert(!Previous.isAmbiguous() && "Ambiguity in class template redecl?");
439 NamedDecl *PrevDecl = 0;
440 if (Previous.begin() != Previous.end())
441 PrevDecl = *Previous.begin();
442
Douglas Gregorc19ee3e2009-06-17 23:37:01 +0000443 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
444 PrevDecl = 0;
445
Douglas Gregorddc29e12009-02-06 22:42:48 +0000446 DeclContext *SemanticContext = CurContext;
447 if (SS.isNotEmpty() && !SS.isInvalid()) {
Douglas Gregore4e5b052009-03-19 00:18:19 +0000448 SemanticContext = computeDeclContext(SS);
Douglas Gregorddc29e12009-02-06 22:42:48 +0000449
Mike Stump390b4cc2009-05-16 07:39:55 +0000450 // FIXME: need to match up several levels of template parameter lists here.
Douglas Gregorddc29e12009-02-06 22:42:48 +0000451 }
452
453 // FIXME: member templates!
454 TemplateParameterList *TemplateParams
455 = static_cast<TemplateParameterList *>(*TemplateParameterLists.release());
456
457 // If there is a previous declaration with the same name, check
458 // whether this is a valid redeclaration.
459 ClassTemplateDecl *PrevClassTemplate
460 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
461 if (PrevClassTemplate) {
462 // Ensure that the template parameter lists are compatible.
463 if (!TemplateParameterListsAreEqual(TemplateParams,
464 PrevClassTemplate->getTemplateParameters(),
465 /*Complain=*/true))
Douglas Gregor212e81c2009-03-25 00:13:59 +0000466 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000467
468 // C++ [temp.class]p4:
469 // In a redeclaration, partial specialization, explicit
470 // specialization or explicit instantiation of a class template,
471 // the class-key shall agree in kind with the original class
472 // template declaration (7.1.5.3).
473 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Douglas Gregor501c5ce2009-05-14 16:41:31 +0000474 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind, KWLoc, *Name)) {
Douglas Gregora3a83512009-04-01 23:51:29 +0000475 Diag(KWLoc, diag::err_use_with_wrong_tag)
476 << Name
477 << CodeModificationHint::CreateReplacement(KWLoc,
478 PrevRecordDecl->getKindName());
Douglas Gregorddc29e12009-02-06 22:42:48 +0000479 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregora3a83512009-04-01 23:51:29 +0000480 Kind = PrevRecordDecl->getTagKind();
Douglas Gregorddc29e12009-02-06 22:42:48 +0000481 }
482
Douglas Gregorddc29e12009-02-06 22:42:48 +0000483 // Check for redefinition of this class template.
484 if (TK == TK_Definition) {
485 if (TagDecl *Def = PrevRecordDecl->getDefinition(Context)) {
486 Diag(NameLoc, diag::err_redefinition) << Name;
487 Diag(Def->getLocation(), diag::note_previous_definition);
488 // FIXME: Would it make sense to try to "forget" the previous
489 // definition, as part of error recovery?
Douglas Gregor212e81c2009-03-25 00:13:59 +0000490 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000491 }
492 }
493 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
494 // Maybe we will complain about the shadowed template parameter.
495 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
496 // Just pretend that we didn't see the previous declaration.
497 PrevDecl = 0;
498 } else if (PrevDecl) {
499 // C++ [temp]p5:
500 // A class template shall not have the same name as any other
501 // template, class, function, object, enumeration, enumerator,
502 // namespace, or type in the same scope (3.3), except as specified
503 // in (14.5.4).
504 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
505 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor212e81c2009-03-25 00:13:59 +0000506 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000507 }
508
Douglas Gregord684b002009-02-10 19:49:53 +0000509 // Check the template parameter list of this declaration, possibly
510 // merging in the template parameter list from the previous class
511 // template declaration.
512 if (CheckTemplateParameterList(TemplateParams,
513 PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0))
514 Invalid = true;
515
Douglas Gregor7da97d02009-05-10 22:57:19 +0000516 // FIXME: If we had a scope specifier, we better have a previous template
Douglas Gregorddc29e12009-02-06 22:42:48 +0000517 // declaration!
518
Douglas Gregorbefc20e2009-03-26 00:10:35 +0000519 CXXRecordDecl *NewClass =
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000520 CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name, KWLoc,
Douglas Gregorddc29e12009-02-06 22:42:48 +0000521 PrevClassTemplate?
Douglas Gregoraafc0cc2009-05-15 19:11:46 +0000522 PrevClassTemplate->getTemplatedDecl() : 0,
523 /*DelayTypeCreation=*/true);
Douglas Gregorddc29e12009-02-06 22:42:48 +0000524
525 ClassTemplateDecl *NewTemplate
526 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
527 DeclarationName(Name), TemplateParams,
Douglas Gregor5953d8b2009-03-19 17:26:29 +0000528 NewClass, PrevClassTemplate);
Douglas Gregorbefc20e2009-03-26 00:10:35 +0000529 NewClass->setDescribedClassTemplate(NewTemplate);
530
Douglas Gregoraafc0cc2009-05-15 19:11:46 +0000531 // Build the type for the class template declaration now.
532 QualType T =
533 Context.getTypeDeclType(NewClass,
534 PrevClassTemplate?
535 PrevClassTemplate->getTemplatedDecl() : 0);
536 assert(T->isDependentType() && "Class template type is not dependent?");
537 (void)T;
538
Anders Carlsson4cbe82c2009-03-26 01:24:28 +0000539 // Set the access specifier.
540 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
541
Douglas Gregorddc29e12009-02-06 22:42:48 +0000542 // Set the lexical context of these templates
543 NewClass->setLexicalDeclContext(CurContext);
544 NewTemplate->setLexicalDeclContext(CurContext);
545
546 if (TK == TK_Definition)
547 NewClass->startDefinition();
548
549 if (Attr)
Douglas Gregor9cdda0c2009-06-17 21:51:59 +0000550 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregorddc29e12009-02-06 22:42:48 +0000551
552 PushOnScopeChains(NewTemplate, S);
553
Douglas Gregord684b002009-02-10 19:49:53 +0000554 if (Invalid) {
555 NewTemplate->setInvalidDecl();
556 NewClass->setInvalidDecl();
557 }
Chris Lattnerb28317a2009-03-28 19:18:32 +0000558 return DeclPtrTy::make(NewTemplate);
Douglas Gregorddc29e12009-02-06 22:42:48 +0000559}
560
Douglas Gregord684b002009-02-10 19:49:53 +0000561/// \brief Checks the validity of a template parameter list, possibly
562/// considering the template parameter list from a previous
563/// declaration.
564///
565/// If an "old" template parameter list is provided, it must be
566/// equivalent (per TemplateParameterListsAreEqual) to the "new"
567/// template parameter list.
568///
569/// \param NewParams Template parameter list for a new template
570/// declaration. This template parameter list will be updated with any
571/// default arguments that are carried through from the previous
572/// template parameter list.
573///
574/// \param OldParams If provided, template parameter list from a
575/// previous declaration of the same template. Default template
576/// arguments will be merged from the old template parameter list to
577/// the new template parameter list.
578///
579/// \returns true if an error occurred, false otherwise.
580bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
581 TemplateParameterList *OldParams) {
582 bool Invalid = false;
583
584 // C++ [temp.param]p10:
585 // The set of default template-arguments available for use with a
586 // template declaration or definition is obtained by merging the
587 // default arguments from the definition (if in scope) and all
588 // declarations in scope in the same way default function
589 // arguments are (8.3.6).
590 bool SawDefaultArgument = false;
591 SourceLocation PreviousDefaultArgLoc;
Douglas Gregorc15cb382009-02-09 23:23:08 +0000592
Anders Carlsson49d25572009-06-12 23:20:15 +0000593 bool SawParameterPack = false;
594 SourceLocation ParameterPackLoc;
595
Mike Stump1a35fde2009-02-11 23:03:27 +0000596 // Dummy initialization to avoid warnings.
Douglas Gregor1bc69132009-02-11 20:46:19 +0000597 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregord684b002009-02-10 19:49:53 +0000598 if (OldParams)
599 OldParam = OldParams->begin();
600
601 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
602 NewParamEnd = NewParams->end();
603 NewParam != NewParamEnd; ++NewParam) {
604 // Variables used to diagnose redundant default arguments
605 bool RedundantDefaultArg = false;
606 SourceLocation OldDefaultLoc;
607 SourceLocation NewDefaultLoc;
608
609 // Variables used to diagnose missing default arguments
610 bool MissingDefaultArg = false;
611
Anders Carlsson49d25572009-06-12 23:20:15 +0000612 // C++0x [temp.param]p11:
613 // If a template parameter of a class template is a template parameter pack,
614 // it must be the last template parameter.
615 if (SawParameterPack) {
616 Diag(ParameterPackLoc,
617 diag::err_template_param_pack_must_be_last_template_parameter);
618 Invalid = true;
619 }
620
Douglas Gregord684b002009-02-10 19:49:53 +0000621 // Merge default arguments for template type parameters.
622 if (TemplateTypeParmDecl *NewTypeParm
623 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
624 TemplateTypeParmDecl *OldTypeParm
625 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
626
Anders Carlsson49d25572009-06-12 23:20:15 +0000627 if (NewTypeParm->isParameterPack()) {
628 assert(!NewTypeParm->hasDefaultArgument() &&
629 "Parameter packs can't have a default argument!");
630 SawParameterPack = true;
631 ParameterPackLoc = NewTypeParm->getLocation();
632 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
Douglas Gregord684b002009-02-10 19:49:53 +0000633 NewTypeParm->hasDefaultArgument()) {
634 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
635 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
636 SawDefaultArgument = true;
637 RedundantDefaultArg = true;
638 PreviousDefaultArgLoc = NewDefaultLoc;
639 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
640 // Merge the default argument from the old declaration to the
641 // new declaration.
642 SawDefaultArgument = true;
643 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgument(),
644 OldTypeParm->getDefaultArgumentLoc(),
645 true);
646 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
647 } else if (NewTypeParm->hasDefaultArgument()) {
648 SawDefaultArgument = true;
649 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
650 } else if (SawDefaultArgument)
651 MissingDefaultArg = true;
652 }
653 // Merge default arguments for non-type template parameters
654 else if (NonTypeTemplateParmDecl *NewNonTypeParm
655 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
656 NonTypeTemplateParmDecl *OldNonTypeParm
657 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
658 if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
659 NewNonTypeParm->hasDefaultArgument()) {
660 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
661 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
662 SawDefaultArgument = true;
663 RedundantDefaultArg = true;
664 PreviousDefaultArgLoc = NewDefaultLoc;
665 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
666 // Merge the default argument from the old declaration to the
667 // new declaration.
668 SawDefaultArgument = true;
669 // FIXME: We need to create a new kind of "default argument"
670 // expression that points to a previous template template
671 // parameter.
672 NewNonTypeParm->setDefaultArgument(
673 OldNonTypeParm->getDefaultArgument());
674 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
675 } else if (NewNonTypeParm->hasDefaultArgument()) {
676 SawDefaultArgument = true;
677 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
678 } else if (SawDefaultArgument)
679 MissingDefaultArg = true;
680 }
681 // Merge default arguments for template template parameters
682 else {
683 TemplateTemplateParmDecl *NewTemplateParm
684 = cast<TemplateTemplateParmDecl>(*NewParam);
685 TemplateTemplateParmDecl *OldTemplateParm
686 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
687 if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
688 NewTemplateParm->hasDefaultArgument()) {
689 OldDefaultLoc = OldTemplateParm->getDefaultArgumentLoc();
690 NewDefaultLoc = NewTemplateParm->getDefaultArgumentLoc();
691 SawDefaultArgument = true;
692 RedundantDefaultArg = true;
693 PreviousDefaultArgLoc = NewDefaultLoc;
694 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
695 // Merge the default argument from the old declaration to the
696 // new declaration.
697 SawDefaultArgument = true;
Mike Stump390b4cc2009-05-16 07:39:55 +0000698 // FIXME: We need to create a new kind of "default argument" expression
699 // that points to a previous template template parameter.
Douglas Gregord684b002009-02-10 19:49:53 +0000700 NewTemplateParm->setDefaultArgument(
701 OldTemplateParm->getDefaultArgument());
702 PreviousDefaultArgLoc = OldTemplateParm->getDefaultArgumentLoc();
703 } else if (NewTemplateParm->hasDefaultArgument()) {
704 SawDefaultArgument = true;
705 PreviousDefaultArgLoc = NewTemplateParm->getDefaultArgumentLoc();
706 } else if (SawDefaultArgument)
707 MissingDefaultArg = true;
708 }
709
710 if (RedundantDefaultArg) {
711 // C++ [temp.param]p12:
712 // A template-parameter shall not be given default arguments
713 // by two different declarations in the same scope.
714 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
715 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
716 Invalid = true;
717 } else if (MissingDefaultArg) {
718 // C++ [temp.param]p11:
719 // If a template-parameter has a default template-argument,
720 // all subsequent template-parameters shall have a default
721 // template-argument supplied.
722 Diag((*NewParam)->getLocation(),
723 diag::err_template_param_default_arg_missing);
724 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
725 Invalid = true;
726 }
727
728 // If we have an old template parameter list that we're merging
729 // in, move on to the next parameter.
730 if (OldParams)
731 ++OldParam;
732 }
733
734 return Invalid;
735}
Douglas Gregorc15cb382009-02-09 23:23:08 +0000736
Douglas Gregorf59a56e2009-07-21 23:53:31 +0000737/// \brief Match the given template parameter lists to the given scope
738/// specifier, returning the template parameter list that applies to the
739/// name.
740///
741/// \param DeclStartLoc the start of the declaration that has a scope
742/// specifier or a template parameter list.
743///
744/// \param SS the scope specifier that will be matched to the given template
745/// parameter lists. This scope specifier precedes a qualified name that is
746/// being declared.
747///
748/// \param ParamLists the template parameter lists, from the outermost to the
749/// innermost template parameter lists.
750///
751/// \param NumParamLists the number of template parameter lists in ParamLists.
752///
753/// \returns the template parameter list, if any, that corresponds to the
754/// name that is preceded by the scope specifier @p SS. This template
755/// parameter list may be have template parameters (if we're declaring a
756/// template) or may have no template parameters (if we're declaring a
757/// template specialization), or may be NULL (if we were's declaring isn't
758/// itself a template).
759TemplateParameterList *
760Sema::MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc,
761 const CXXScopeSpec &SS,
762 TemplateParameterList **ParamLists,
763 unsigned NumParamLists) {
764 // FIXME: This routine will need a lot more testing once we have support for
765 // member templates.
766
767 // Find the template-ids that occur within the nested-name-specifier. These
768 // template-ids will match up with the template parameter lists.
769 llvm::SmallVector<const TemplateSpecializationType *, 4>
770 TemplateIdsInSpecifier;
771 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
772 NNS; NNS = NNS->getPrefix()) {
773 if (const TemplateSpecializationType *SpecType
774 = dyn_cast_or_null<TemplateSpecializationType>(NNS->getAsType())) {
775 TemplateDecl *Template = SpecType->getTemplateName().getAsTemplateDecl();
776 if (!Template)
777 continue; // FIXME: should this be an error? probably...
778
779 if (const RecordType *Record = SpecType->getAsRecordType()) {
780 ClassTemplateSpecializationDecl *SpecDecl
781 = cast<ClassTemplateSpecializationDecl>(Record->getDecl());
782 // If the nested name specifier refers to an explicit specialization,
783 // we don't need a template<> header.
784 if (SpecDecl->getSpecializationKind() == TSK_ExplicitSpecialization)
785 continue;
786 }
787
788 TemplateIdsInSpecifier.push_back(SpecType);
789 }
790 }
791
792 // Reverse the list of template-ids in the scope specifier, so that we can
793 // more easily match up the template-ids and the template parameter lists.
794 std::reverse(TemplateIdsInSpecifier.begin(), TemplateIdsInSpecifier.end());
795
796 SourceLocation FirstTemplateLoc = DeclStartLoc;
797 if (NumParamLists)
798 FirstTemplateLoc = ParamLists[0]->getTemplateLoc();
799
800 // Match the template-ids found in the specifier to the template parameter
801 // lists.
802 unsigned Idx = 0;
803 for (unsigned NumTemplateIds = TemplateIdsInSpecifier.size();
804 Idx != NumTemplateIds; ++Idx) {
805 bool DependentTemplateId = TemplateIdsInSpecifier[Idx]->isDependentType();
806 if (Idx >= NumParamLists) {
807 // We have a template-id without a corresponding template parameter
808 // list.
809 if (DependentTemplateId) {
810 // FIXME: the location information here isn't great.
811 Diag(SS.getRange().getBegin(),
812 diag::err_template_spec_needs_template_parameters)
813 << QualType(TemplateIdsInSpecifier[Idx], 0)
814 << SS.getRange();
815 } else {
816 Diag(SS.getRange().getBegin(), diag::err_template_spec_needs_header)
817 << SS.getRange()
818 << CodeModificationHint::CreateInsertion(FirstTemplateLoc,
819 "template<> ");
820 }
821 return 0;
822 }
823
824 // Check the template parameter list against its corresponding template-id.
825 TemplateDecl *Template
826 = TemplateIdsInSpecifier[Idx]->getTemplateName().getAsTemplateDecl();
827 TemplateParameterListsAreEqual(ParamLists[Idx],
828 Template->getTemplateParameters(),
829 true);
830 }
831
832 // If there were at least as many template-ids as there were template
833 // parameter lists, then there are no template parameter lists remaining for
834 // the declaration itself.
835 if (Idx >= NumParamLists)
836 return 0;
837
838 // If there were too many template parameter lists, complain about that now.
839 if (Idx != NumParamLists - 1) {
840 while (Idx < NumParamLists - 1) {
841 Diag(ParamLists[Idx]->getTemplateLoc(),
842 diag::err_template_spec_extra_headers)
843 << SourceRange(ParamLists[Idx]->getTemplateLoc(),
844 ParamLists[Idx]->getRAngleLoc());
845 ++Idx;
846 }
847 }
848
849 // Return the last template parameter list, which corresponds to the
850 // entity being declared.
851 return ParamLists[NumParamLists - 1];
852}
853
Douglas Gregor40808ce2009-03-09 23:48:35 +0000854/// \brief Translates template arguments as provided by the parser
855/// into template arguments used by semantic analysis.
856static void
857translateTemplateArguments(ASTTemplateArgsPtr &TemplateArgsIn,
858 SourceLocation *TemplateArgLocs,
859 llvm::SmallVector<TemplateArgument, 16> &TemplateArgs) {
860 TemplateArgs.reserve(TemplateArgsIn.size());
861
862 void **Args = TemplateArgsIn.getArgs();
863 bool *ArgIsType = TemplateArgsIn.getArgIsType();
864 for (unsigned Arg = 0, Last = TemplateArgsIn.size(); Arg != Last; ++Arg) {
865 TemplateArgs.push_back(
866 ArgIsType[Arg]? TemplateArgument(TemplateArgLocs[Arg],
867 QualType::getFromOpaquePtr(Args[Arg]))
868 : TemplateArgument(reinterpret_cast<Expr *>(Args[Arg])));
869 }
870}
871
Douglas Gregor7532dc62009-03-30 22:58:21 +0000872QualType Sema::CheckTemplateIdType(TemplateName Name,
873 SourceLocation TemplateLoc,
874 SourceLocation LAngleLoc,
875 const TemplateArgument *TemplateArgs,
876 unsigned NumTemplateArgs,
877 SourceLocation RAngleLoc) {
878 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregorc45c2322009-03-31 00:43:58 +0000879 if (!Template) {
880 // The template name does not resolve to a template, so we just
881 // build a dependent template-id type.
Douglas Gregorc45c2322009-03-31 00:43:58 +0000882 return Context.getTemplateSpecializationType(Name, TemplateArgs,
Douglas Gregor1275ae02009-07-28 23:00:59 +0000883 NumTemplateArgs);
Douglas Gregorc45c2322009-03-31 00:43:58 +0000884 }
Douglas Gregor7532dc62009-03-30 22:58:21 +0000885
Douglas Gregor40808ce2009-03-09 23:48:35 +0000886 // Check that the template argument list is well-formed for this
887 // template.
Anders Carlssonfb250522009-06-23 01:26:57 +0000888 TemplateArgumentListBuilder Converted(Template->getTemplateParameters(),
889 NumTemplateArgs);
Douglas Gregor7532dc62009-03-30 22:58:21 +0000890 if (CheckTemplateArgumentList(Template, TemplateLoc, LAngleLoc,
Douglas Gregor40808ce2009-03-09 23:48:35 +0000891 TemplateArgs, NumTemplateArgs, RAngleLoc,
Douglas Gregor16134c62009-07-01 00:28:38 +0000892 false, Converted))
Douglas Gregor40808ce2009-03-09 23:48:35 +0000893 return QualType();
894
Anders Carlssonfb250522009-06-23 01:26:57 +0000895 assert((Converted.structuredSize() ==
Douglas Gregor7532dc62009-03-30 22:58:21 +0000896 Template->getTemplateParameters()->size()) &&
Douglas Gregor40808ce2009-03-09 23:48:35 +0000897 "Converted template argument list is too short!");
898
899 QualType CanonType;
900
Douglas Gregor7532dc62009-03-30 22:58:21 +0000901 if (TemplateSpecializationType::anyDependentTemplateArguments(
Douglas Gregor40808ce2009-03-09 23:48:35 +0000902 TemplateArgs,
903 NumTemplateArgs)) {
904 // This class template specialization is a dependent
905 // type. Therefore, its canonical type is another class template
906 // specialization type that contains all of the converted
907 // arguments in canonical form. This ensures that, e.g., A<T> and
908 // A<T, T> have identical types when A is declared as:
909 //
910 // template<typename T, typename U = T> struct A;
Douglas Gregor25a3ef72009-05-07 06:41:52 +0000911 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
912 CanonType = Context.getTemplateSpecializationType(CanonName,
Anders Carlssonfb250522009-06-23 01:26:57 +0000913 Converted.getFlatArguments(),
914 Converted.flatSize());
Douglas Gregor1275ae02009-07-28 23:00:59 +0000915
916 // FIXME: CanonType is not actually the canonical type, and unfortunately
917 // it is a TemplateTypeSpecializationType that we will never use again.
918 // In the future, we need to teach getTemplateSpecializationType to only
919 // build the canonical type and return that to us.
920 CanonType = Context.getCanonicalType(CanonType);
Douglas Gregor7532dc62009-03-30 22:58:21 +0000921 } else if (ClassTemplateDecl *ClassTemplate
922 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregor40808ce2009-03-09 23:48:35 +0000923 // Find the class template specialization declaration that
924 // corresponds to these arguments.
925 llvm::FoldingSetNodeID ID;
Anders Carlsson1c5976e2009-06-05 03:43:12 +0000926 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlssonfb250522009-06-23 01:26:57 +0000927 Converted.getFlatArguments(),
Douglas Gregor828e2262009-07-29 16:09:57 +0000928 Converted.flatSize(),
929 Context);
Douglas Gregor40808ce2009-03-09 23:48:35 +0000930 void *InsertPos = 0;
931 ClassTemplateSpecializationDecl *Decl
932 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
933 if (!Decl) {
934 // This is the first time we have referenced this class template
935 // specialization. Create the canonical declaration and add it to
936 // the set of specializations.
937 Decl = ClassTemplateSpecializationDecl::Create(Context,
Anders Carlsson1c5976e2009-06-05 03:43:12 +0000938 ClassTemplate->getDeclContext(),
939 TemplateLoc,
940 ClassTemplate,
Anders Carlssonfb250522009-06-23 01:26:57 +0000941 Converted, 0);
Douglas Gregor40808ce2009-03-09 23:48:35 +0000942 ClassTemplate->getSpecializations().InsertNode(Decl, InsertPos);
943 Decl->setLexicalDeclContext(CurContext);
944 }
945
946 CanonType = Context.getTypeDeclType(Decl);
947 }
948
949 // Build the fully-sugared type for this class template
950 // specialization, which refers back to the class template
951 // specialization we created or found.
Douglas Gregor7532dc62009-03-30 22:58:21 +0000952 return Context.getTemplateSpecializationType(Name, TemplateArgs,
953 NumTemplateArgs, CanonType);
Douglas Gregor40808ce2009-03-09 23:48:35 +0000954}
955
Douglas Gregorcc636682009-02-17 23:15:12 +0000956Action::TypeResult
Douglas Gregor7532dc62009-03-30 22:58:21 +0000957Sema::ActOnTemplateIdType(TemplateTy TemplateD, SourceLocation TemplateLoc,
958 SourceLocation LAngleLoc,
959 ASTTemplateArgsPtr TemplateArgsIn,
960 SourceLocation *TemplateArgLocs,
961 SourceLocation RAngleLoc) {
962 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Douglas Gregor55f6b142009-02-09 18:46:07 +0000963
Douglas Gregor40808ce2009-03-09 23:48:35 +0000964 // Translate the parser's template argument list in our AST format.
965 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
966 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
Douglas Gregorc15cb382009-02-09 23:23:08 +0000967
Douglas Gregor7532dc62009-03-30 22:58:21 +0000968 QualType Result = CheckTemplateIdType(Template, TemplateLoc, LAngleLoc,
Jay Foadbeaaccd2009-05-21 09:52:38 +0000969 TemplateArgs.data(),
970 TemplateArgs.size(),
Douglas Gregor7532dc62009-03-30 22:58:21 +0000971 RAngleLoc);
Douglas Gregor40808ce2009-03-09 23:48:35 +0000972 TemplateArgsIn.release();
Douglas Gregor31a19b62009-04-01 21:51:26 +0000973
974 if (Result.isNull())
975 return true;
976
Douglas Gregor5908e9f2009-02-09 19:34:22 +0000977 return Result.getAsOpaquePtr();
Douglas Gregor55f6b142009-02-09 18:46:07 +0000978}
979
Douglas Gregoredce4dd2009-06-30 22:34:41 +0000980Sema::OwningExprResult Sema::BuildTemplateIdExpr(TemplateName Template,
981 SourceLocation TemplateNameLoc,
982 SourceLocation LAngleLoc,
983 const TemplateArgument *TemplateArgs,
984 unsigned NumTemplateArgs,
985 SourceLocation RAngleLoc) {
986 // FIXME: Can we do any checking at this point? I guess we could check the
987 // template arguments that we have against the template name, if the template
988 // name refers to a single template. That's not a terribly common case,
989 // though.
990 return Owned(TemplateIdRefExpr::Create(Context,
991 /*FIXME: New type?*/Context.OverloadTy,
992 /*FIXME: Necessary?*/0,
993 /*FIXME: Necessary?*/SourceRange(),
994 Template, TemplateNameLoc, LAngleLoc,
995 TemplateArgs,
996 NumTemplateArgs, RAngleLoc));
997}
998
999Sema::OwningExprResult Sema::ActOnTemplateIdExpr(TemplateTy TemplateD,
1000 SourceLocation TemplateNameLoc,
1001 SourceLocation LAngleLoc,
1002 ASTTemplateArgsPtr TemplateArgsIn,
1003 SourceLocation *TemplateArgLocs,
1004 SourceLocation RAngleLoc) {
1005 TemplateName Template = TemplateD.getAsVal<TemplateName>();
1006
1007 // Translate the parser's template argument list in our AST format.
1008 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
1009 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001010 TemplateArgsIn.release();
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001011
1012 return BuildTemplateIdExpr(Template, TemplateNameLoc, LAngleLoc,
1013 TemplateArgs.data(), TemplateArgs.size(),
1014 RAngleLoc);
1015}
1016
Douglas Gregorc45c2322009-03-31 00:43:58 +00001017/// \brief Form a dependent template name.
1018///
1019/// This action forms a dependent template name given the template
1020/// name and its (presumably dependent) scope specifier. For
1021/// example, given "MetaFun::template apply", the scope specifier \p
1022/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
1023/// of the "template" keyword, and "apply" is the \p Name.
1024Sema::TemplateTy
1025Sema::ActOnDependentTemplateName(SourceLocation TemplateKWLoc,
1026 const IdentifierInfo &Name,
1027 SourceLocation NameLoc,
1028 const CXXScopeSpec &SS) {
1029 if (!SS.isSet() || SS.isInvalid())
1030 return TemplateTy();
1031
1032 NestedNameSpecifier *Qualifier
1033 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
1034
1035 // FIXME: member of the current instantiation
1036
1037 if (!Qualifier->isDependent()) {
1038 // C++0x [temp.names]p5:
1039 // If a name prefixed by the keyword template is not the name of
1040 // a template, the program is ill-formed. [Note: the keyword
1041 // template may not be applied to non-template members of class
1042 // templates. -end note ] [ Note: as is the case with the
1043 // typename prefix, the template prefix is allowed in cases
1044 // where it is not strictly necessary; i.e., when the
1045 // nested-name-specifier or the expression on the left of the ->
1046 // or . is not dependent on a template-parameter, or the use
1047 // does not appear in the scope of a template. -end note]
1048 //
1049 // Note: C++03 was more strict here, because it banned the use of
1050 // the "template" keyword prior to a template-name that was not a
1051 // dependent name. C++ DR468 relaxed this requirement (the
1052 // "template" keyword is now permitted). We follow the C++0x
1053 // rules, even in C++03 mode, retroactively applying the DR.
1054 TemplateTy Template;
1055 TemplateNameKind TNK = isTemplateName(Name, 0, Template, &SS);
1056 if (TNK == TNK_Non_template) {
1057 Diag(NameLoc, diag::err_template_kw_refers_to_non_template)
1058 << &Name;
1059 return TemplateTy();
1060 }
1061
1062 return Template;
1063 }
1064
1065 return TemplateTy::make(Context.getDependentTemplateName(Qualifier, &Name));
1066}
1067
Anders Carlsson436b1562009-06-13 00:33:33 +00001068bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
1069 const TemplateArgument &Arg,
1070 TemplateArgumentListBuilder &Converted) {
1071 // Check template type parameter.
1072 if (Arg.getKind() != TemplateArgument::Type) {
1073 // C++ [temp.arg.type]p1:
1074 // A template-argument for a template-parameter which is a
1075 // type shall be a type-id.
1076
1077 // We have a template type parameter but the template argument
1078 // is not a type.
1079 Diag(Arg.getLocation(), diag::err_template_arg_must_be_type);
1080 Diag(Param->getLocation(), diag::note_template_param_here);
1081
1082 return true;
1083 }
1084
1085 if (CheckTemplateArgument(Param, Arg.getAsType(), Arg.getLocation()))
1086 return true;
1087
1088 // Add the converted template type argument.
Anders Carlssonfb250522009-06-23 01:26:57 +00001089 Converted.Append(
Anders Carlsson436b1562009-06-13 00:33:33 +00001090 TemplateArgument(Arg.getLocation(),
1091 Context.getCanonicalType(Arg.getAsType())));
1092 return false;
1093}
1094
Douglas Gregorc15cb382009-02-09 23:23:08 +00001095/// \brief Check that the given template argument list is well-formed
1096/// for specializing the given template.
1097bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
1098 SourceLocation TemplateLoc,
1099 SourceLocation LAngleLoc,
Douglas Gregor40808ce2009-03-09 23:48:35 +00001100 const TemplateArgument *TemplateArgs,
1101 unsigned NumTemplateArgs,
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001102 SourceLocation RAngleLoc,
Douglas Gregor16134c62009-07-01 00:28:38 +00001103 bool PartialTemplateArgs,
Anders Carlsson1c5976e2009-06-05 03:43:12 +00001104 TemplateArgumentListBuilder &Converted) {
Douglas Gregorc15cb382009-02-09 23:23:08 +00001105 TemplateParameterList *Params = Template->getTemplateParameters();
1106 unsigned NumParams = Params->size();
Douglas Gregor40808ce2009-03-09 23:48:35 +00001107 unsigned NumArgs = NumTemplateArgs;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001108 bool Invalid = false;
1109
Anders Carlsson0ceffb52009-06-13 02:08:00 +00001110 bool HasParameterPack =
1111 NumParams > 0 && Params->getParam(NumParams - 1)->isTemplateParameterPack();
1112
1113 if ((NumArgs > NumParams && !HasParameterPack) ||
Douglas Gregor16134c62009-07-01 00:28:38 +00001114 (NumArgs < Params->getMinRequiredArguments() &&
1115 !PartialTemplateArgs)) {
Douglas Gregorc15cb382009-02-09 23:23:08 +00001116 // FIXME: point at either the first arg beyond what we can handle,
1117 // or the '>', depending on whether we have too many or too few
1118 // arguments.
1119 SourceRange Range;
1120 if (NumArgs > NumParams)
Douglas Gregor40808ce2009-03-09 23:48:35 +00001121 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
Douglas Gregorc15cb382009-02-09 23:23:08 +00001122 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
1123 << (NumArgs > NumParams)
1124 << (isa<ClassTemplateDecl>(Template)? 0 :
1125 isa<FunctionTemplateDecl>(Template)? 1 :
1126 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
1127 << Template << Range;
Douglas Gregor62cb18d2009-02-11 18:16:40 +00001128 Diag(Template->getLocation(), diag::note_template_decl_here)
1129 << Params->getSourceRange();
Douglas Gregorc15cb382009-02-09 23:23:08 +00001130 Invalid = true;
1131 }
1132
1133 // C++ [temp.arg]p1:
1134 // [...] The type and form of each template-argument specified in
1135 // a template-id shall match the type and form specified for the
1136 // corresponding parameter declared by the template in its
1137 // template-parameter-list.
1138 unsigned ArgIdx = 0;
1139 for (TemplateParameterList::iterator Param = Params->begin(),
1140 ParamEnd = Params->end();
1141 Param != ParamEnd; ++Param, ++ArgIdx) {
Douglas Gregor16134c62009-07-01 00:28:38 +00001142 if (ArgIdx > NumArgs && PartialTemplateArgs)
1143 break;
1144
Douglas Gregorc15cb382009-02-09 23:23:08 +00001145 // Decode the template argument
Douglas Gregor40808ce2009-03-09 23:48:35 +00001146 TemplateArgument Arg;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001147 if (ArgIdx >= NumArgs) {
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001148 // Retrieve the default template argument from the template
1149 // parameter.
1150 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
Anders Carlsson0ceffb52009-06-13 02:08:00 +00001151 if (TTP->isParameterPack()) {
Anders Carlssonfb250522009-06-23 01:26:57 +00001152 // We have an empty argument pack.
1153 Converted.BeginPack();
1154 Converted.EndPack();
Anders Carlsson0ceffb52009-06-13 02:08:00 +00001155 break;
1156 }
1157
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001158 if (!TTP->hasDefaultArgument())
1159 break;
1160
Douglas Gregor40808ce2009-03-09 23:48:35 +00001161 QualType ArgType = TTP->getDefaultArgument();
Douglas Gregor99ebf652009-02-27 19:31:52 +00001162
1163 // If the argument type is dependent, instantiate it now based
1164 // on the previously-computed template arguments.
Douglas Gregordf667e72009-03-10 20:44:00 +00001165 if (ArgType->isDependentType()) {
1166 InstantiatingTemplate Inst(*this, TemplateLoc,
Anders Carlssonfb250522009-06-23 01:26:57 +00001167 Template, Converted.getFlatArguments(),
Anders Carlsson1c5976e2009-06-05 03:43:12 +00001168 Converted.flatSize(),
Douglas Gregordf667e72009-03-10 20:44:00 +00001169 SourceRange(TemplateLoc, RAngleLoc));
Douglas Gregor7e063902009-05-11 23:53:27 +00001170
Anders Carlssone9c904b2009-06-05 04:47:51 +00001171 TemplateArgumentList TemplateArgs(Context, Converted,
Anders Carlssonfb250522009-06-23 01:26:57 +00001172 /*TakeArgs=*/false);
Douglas Gregor7e063902009-05-11 23:53:27 +00001173 ArgType = InstantiateType(ArgType, TemplateArgs,
Douglas Gregor99ebf652009-02-27 19:31:52 +00001174 TTP->getDefaultArgumentLoc(),
1175 TTP->getDeclName());
Douglas Gregordf667e72009-03-10 20:44:00 +00001176 }
Douglas Gregor99ebf652009-02-27 19:31:52 +00001177
1178 if (ArgType.isNull())
Douglas Gregorcd281c32009-02-28 00:25:32 +00001179 return true;
Douglas Gregor99ebf652009-02-27 19:31:52 +00001180
Douglas Gregor40808ce2009-03-09 23:48:35 +00001181 Arg = TemplateArgument(TTP->getLocation(), ArgType);
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001182 } else if (NonTypeTemplateParmDecl *NTTP
1183 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
1184 if (!NTTP->hasDefaultArgument())
1185 break;
1186
Anders Carlsson3b56c002009-06-11 16:06:49 +00001187 InstantiatingTemplate Inst(*this, TemplateLoc,
Anders Carlssonfb250522009-06-23 01:26:57 +00001188 Template, Converted.getFlatArguments(),
Anders Carlsson3b56c002009-06-11 16:06:49 +00001189 Converted.flatSize(),
1190 SourceRange(TemplateLoc, RAngleLoc));
1191
1192 TemplateArgumentList TemplateArgs(Context, Converted,
Anders Carlssonfb250522009-06-23 01:26:57 +00001193 /*TakeArgs=*/false);
Anders Carlsson3b56c002009-06-11 16:06:49 +00001194
1195 Sema::OwningExprResult E = InstantiateExpr(NTTP->getDefaultArgument(),
1196 TemplateArgs);
1197 if (E.isInvalid())
1198 return true;
1199
1200 Arg = TemplateArgument(E.takeAs<Expr>());
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001201 } else {
1202 TemplateTemplateParmDecl *TempParm
1203 = cast<TemplateTemplateParmDecl>(*Param);
1204
1205 if (!TempParm->hasDefaultArgument())
1206 break;
1207
Douglas Gregor2943aed2009-03-03 04:44:36 +00001208 // FIXME: Instantiate default argument
Douglas Gregor40808ce2009-03-09 23:48:35 +00001209 Arg = TemplateArgument(TempParm->getDefaultArgument());
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001210 }
1211 } else {
1212 // Retrieve the template argument produced by the user.
Douglas Gregor40808ce2009-03-09 23:48:35 +00001213 Arg = TemplateArgs[ArgIdx];
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001214 }
1215
Douglas Gregorc15cb382009-02-09 23:23:08 +00001216
1217 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
Anders Carlsson0ceffb52009-06-13 02:08:00 +00001218 if (TTP->isParameterPack()) {
Anders Carlssonfb250522009-06-23 01:26:57 +00001219 Converted.BeginPack();
Anders Carlsson0ceffb52009-06-13 02:08:00 +00001220 // Check all the remaining arguments (if any).
1221 for (; ArgIdx < NumArgs; ++ArgIdx) {
1222 if (CheckTemplateTypeArgument(TTP, TemplateArgs[ArgIdx], Converted))
1223 Invalid = true;
1224 }
1225
Anders Carlssonfb250522009-06-23 01:26:57 +00001226 Converted.EndPack();
Anders Carlsson0ceffb52009-06-13 02:08:00 +00001227 } else {
1228 if (CheckTemplateTypeArgument(TTP, Arg, Converted))
1229 Invalid = true;
1230 }
Douglas Gregorc15cb382009-02-09 23:23:08 +00001231 } else if (NonTypeTemplateParmDecl *NTTP
1232 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
1233 // Check non-type template parameters.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001234
1235 // Instantiate the type of the non-type template parameter with
1236 // the template arguments we've seen thus far.
1237 QualType NTTPType = NTTP->getType();
1238 if (NTTPType->isDependentType()) {
1239 // Instantiate the type of the non-type template parameter.
Douglas Gregordf667e72009-03-10 20:44:00 +00001240 InstantiatingTemplate Inst(*this, TemplateLoc,
Anders Carlssonfb250522009-06-23 01:26:57 +00001241 Template, Converted.getFlatArguments(),
Anders Carlsson1c5976e2009-06-05 03:43:12 +00001242 Converted.flatSize(),
Douglas Gregordf667e72009-03-10 20:44:00 +00001243 SourceRange(TemplateLoc, RAngleLoc));
1244
Anders Carlssone9c904b2009-06-05 04:47:51 +00001245 TemplateArgumentList TemplateArgs(Context, Converted,
Anders Carlssonfb250522009-06-23 01:26:57 +00001246 /*TakeArgs=*/false);
Douglas Gregor7e063902009-05-11 23:53:27 +00001247 NTTPType = InstantiateType(NTTPType, TemplateArgs,
Douglas Gregor2943aed2009-03-03 04:44:36 +00001248 NTTP->getLocation(),
1249 NTTP->getDeclName());
1250 // If that worked, check the non-type template parameter type
1251 // for validity.
1252 if (!NTTPType.isNull())
1253 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
1254 NTTP->getLocation());
Douglas Gregor2943aed2009-03-03 04:44:36 +00001255 if (NTTPType.isNull()) {
1256 Invalid = true;
1257 break;
1258 }
1259 }
1260
Douglas Gregor40808ce2009-03-09 23:48:35 +00001261 switch (Arg.getKind()) {
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001262 case TemplateArgument::Null:
1263 assert(false && "Should never see a NULL template argument here");
1264 break;
1265
Douglas Gregor40808ce2009-03-09 23:48:35 +00001266 case TemplateArgument::Expression: {
1267 Expr *E = Arg.getAsExpr();
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001268 TemplateArgument Result;
1269 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
Douglas Gregorc15cb382009-02-09 23:23:08 +00001270 Invalid = true;
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001271 else
Anders Carlssonfb250522009-06-23 01:26:57 +00001272 Converted.Append(Result);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001273 break;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001274 }
1275
Douglas Gregor40808ce2009-03-09 23:48:35 +00001276 case TemplateArgument::Declaration:
1277 case TemplateArgument::Integral:
1278 // We've already checked this template argument, so just copy
1279 // it to the list of converted arguments.
Anders Carlssonfb250522009-06-23 01:26:57 +00001280 Converted.Append(Arg);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001281 break;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001282
Douglas Gregor40808ce2009-03-09 23:48:35 +00001283 case TemplateArgument::Type:
1284 // We have a non-type template parameter but the template
1285 // argument is a type.
1286
1287 // C++ [temp.arg]p2:
1288 // In a template-argument, an ambiguity between a type-id and
1289 // an expression is resolved to a type-id, regardless of the
1290 // form of the corresponding template-parameter.
1291 //
1292 // We warn specifically about this case, since it can be rather
1293 // confusing for users.
1294 if (Arg.getAsType()->isFunctionType())
1295 Diag(Arg.getLocation(), diag::err_template_arg_nontype_ambig)
1296 << Arg.getAsType();
1297 else
1298 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr);
1299 Diag((*Param)->getLocation(), diag::note_template_param_here);
1300 Invalid = true;
Anders Carlssond01b1da2009-06-15 17:04:53 +00001301 break;
1302
1303 case TemplateArgument::Pack:
1304 assert(0 && "FIXME: Implement!");
1305 break;
Douglas Gregor40808ce2009-03-09 23:48:35 +00001306 }
Douglas Gregorc15cb382009-02-09 23:23:08 +00001307 } else {
1308 // Check template template parameters.
1309 TemplateTemplateParmDecl *TempParm
1310 = cast<TemplateTemplateParmDecl>(*Param);
1311
Douglas Gregor40808ce2009-03-09 23:48:35 +00001312 switch (Arg.getKind()) {
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001313 case TemplateArgument::Null:
1314 assert(false && "Should never see a NULL template argument here");
1315 break;
1316
Douglas Gregor40808ce2009-03-09 23:48:35 +00001317 case TemplateArgument::Expression: {
1318 Expr *ArgExpr = Arg.getAsExpr();
1319 if (ArgExpr && isa<DeclRefExpr>(ArgExpr) &&
1320 isa<TemplateDecl>(cast<DeclRefExpr>(ArgExpr)->getDecl())) {
1321 if (CheckTemplateArgument(TempParm, cast<DeclRefExpr>(ArgExpr)))
1322 Invalid = true;
1323
1324 // Add the converted template argument.
Douglas Gregor7da97d02009-05-10 22:57:19 +00001325 Decl *D
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00001326 = cast<DeclRefExpr>(ArgExpr)->getDecl()->getCanonicalDecl();
Anders Carlssonfb250522009-06-23 01:26:57 +00001327 Converted.Append(TemplateArgument(Arg.getLocation(), D));
Douglas Gregor40808ce2009-03-09 23:48:35 +00001328 continue;
1329 }
1330 }
1331 // fall through
1332
1333 case TemplateArgument::Type: {
1334 // We have a template template parameter but the template
1335 // argument does not refer to a template.
1336 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
1337 Invalid = true;
1338 break;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001339 }
1340
Douglas Gregor40808ce2009-03-09 23:48:35 +00001341 case TemplateArgument::Declaration:
1342 // We've already checked this template argument, so just copy
1343 // it to the list of converted arguments.
Anders Carlssonfb250522009-06-23 01:26:57 +00001344 Converted.Append(Arg);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001345 break;
1346
1347 case TemplateArgument::Integral:
1348 assert(false && "Integral argument with template template parameter");
1349 break;
Anders Carlssond01b1da2009-06-15 17:04:53 +00001350
1351 case TemplateArgument::Pack:
1352 assert(0 && "FIXME: Implement!");
1353 break;
Douglas Gregor40808ce2009-03-09 23:48:35 +00001354 }
Douglas Gregorc15cb382009-02-09 23:23:08 +00001355 }
1356 }
1357
1358 return Invalid;
1359}
1360
1361/// \brief Check a template argument against its corresponding
1362/// template type parameter.
1363///
1364/// This routine implements the semantics of C++ [temp.arg.type]. It
1365/// returns true if an error occurred, and false otherwise.
1366bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
1367 QualType Arg, SourceLocation ArgLoc) {
1368 // C++ [temp.arg.type]p2:
1369 // A local type, a type with no linkage, an unnamed type or a type
1370 // compounded from any of these types shall not be used as a
1371 // template-argument for a template type-parameter.
1372 //
1373 // FIXME: Perform the recursive and no-linkage type checks.
1374 const TagType *Tag = 0;
1375 if (const EnumType *EnumT = Arg->getAsEnumType())
1376 Tag = EnumT;
Ted Kremenek35366a62009-07-17 17:50:17 +00001377 else if (const RecordType *RecordT = Arg->getAsRecordType())
Douglas Gregorc15cb382009-02-09 23:23:08 +00001378 Tag = RecordT;
1379 if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod())
1380 return Diag(ArgLoc, diag::err_template_arg_local_type)
1381 << QualType(Tag, 0);
Douglas Gregor98137532009-03-10 18:33:27 +00001382 else if (Tag && !Tag->getDecl()->getDeclName() &&
1383 !Tag->getDecl()->getTypedefForAnonDecl()) {
Douglas Gregorc15cb382009-02-09 23:23:08 +00001384 Diag(ArgLoc, diag::err_template_arg_unnamed_type);
1385 Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here);
1386 return true;
1387 }
1388
1389 return false;
1390}
1391
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001392/// \brief Checks whether the given template argument is the address
1393/// of an object or function according to C++ [temp.arg.nontype]p1.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001394bool Sema::CheckTemplateArgumentAddressOfObjectOrFunction(Expr *Arg,
1395 NamedDecl *&Entity) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001396 bool Invalid = false;
1397
1398 // See through any implicit casts we added to fix the type.
1399 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
1400 Arg = Cast->getSubExpr();
1401
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001402 // C++0x allows nullptr, and there's no further checking to be done for that.
1403 if (Arg->getType()->isNullPtrType())
1404 return false;
1405
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001406 // C++ [temp.arg.nontype]p1:
1407 //
1408 // A template-argument for a non-type, non-template
1409 // template-parameter shall be one of: [...]
1410 //
1411 // -- the address of an object or function with external
1412 // linkage, including function templates and function
1413 // template-ids but excluding non-static class members,
1414 // expressed as & id-expression where the & is optional if
1415 // the name refers to a function or array, or if the
1416 // corresponding template-parameter is a reference; or
1417 DeclRefExpr *DRE = 0;
1418
1419 // Ignore (and complain about) any excess parentheses.
1420 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
1421 if (!Invalid) {
1422 Diag(Arg->getSourceRange().getBegin(),
1423 diag::err_template_arg_extra_parens)
1424 << Arg->getSourceRange();
1425 Invalid = true;
1426 }
1427
1428 Arg = Parens->getSubExpr();
1429 }
1430
1431 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
1432 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
1433 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
1434 } else
1435 DRE = dyn_cast<DeclRefExpr>(Arg);
1436
1437 if (!DRE || !isa<ValueDecl>(DRE->getDecl()))
1438 return Diag(Arg->getSourceRange().getBegin(),
1439 diag::err_template_arg_not_object_or_func_form)
1440 << Arg->getSourceRange();
1441
1442 // Cannot refer to non-static data members
1443 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl()))
1444 return Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
1445 << Field << Arg->getSourceRange();
1446
1447 // Cannot refer to non-static member functions
1448 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
1449 if (!Method->isStatic())
1450 return Diag(Arg->getSourceRange().getBegin(),
1451 diag::err_template_arg_method)
1452 << Method << Arg->getSourceRange();
1453
1454 // Functions must have external linkage.
1455 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
1456 if (Func->getStorageClass() == FunctionDecl::Static) {
1457 Diag(Arg->getSourceRange().getBegin(),
1458 diag::err_template_arg_function_not_extern)
1459 << Func << Arg->getSourceRange();
1460 Diag(Func->getLocation(), diag::note_template_arg_internal_object)
1461 << true;
1462 return true;
1463 }
1464
1465 // Okay: we've named a function with external linkage.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001466 Entity = Func;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001467 return Invalid;
1468 }
1469
1470 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
1471 if (!Var->hasGlobalStorage()) {
1472 Diag(Arg->getSourceRange().getBegin(),
1473 diag::err_template_arg_object_not_extern)
1474 << Var << Arg->getSourceRange();
1475 Diag(Var->getLocation(), diag::note_template_arg_internal_object)
1476 << true;
1477 return true;
1478 }
1479
1480 // Okay: we've named an object with external linkage
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001481 Entity = Var;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001482 return Invalid;
1483 }
1484
1485 // We found something else, but we don't know specifically what it is.
1486 Diag(Arg->getSourceRange().getBegin(),
1487 diag::err_template_arg_not_object_or_func)
1488 << Arg->getSourceRange();
1489 Diag(DRE->getDecl()->getLocation(),
1490 diag::note_template_arg_refers_here);
1491 return true;
1492}
1493
1494/// \brief Checks whether the given template argument is a pointer to
1495/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001496bool
1497Sema::CheckTemplateArgumentPointerToMember(Expr *Arg, NamedDecl *&Member) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001498 bool Invalid = false;
1499
1500 // See through any implicit casts we added to fix the type.
1501 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
1502 Arg = Cast->getSubExpr();
1503
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001504 // C++0x allows nullptr, and there's no further checking to be done for that.
1505 if (Arg->getType()->isNullPtrType())
1506 return false;
1507
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001508 // C++ [temp.arg.nontype]p1:
1509 //
1510 // A template-argument for a non-type, non-template
1511 // template-parameter shall be one of: [...]
1512 //
1513 // -- a pointer to member expressed as described in 5.3.1.
1514 QualifiedDeclRefExpr *DRE = 0;
1515
1516 // Ignore (and complain about) any excess parentheses.
1517 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
1518 if (!Invalid) {
1519 Diag(Arg->getSourceRange().getBegin(),
1520 diag::err_template_arg_extra_parens)
1521 << Arg->getSourceRange();
1522 Invalid = true;
1523 }
1524
1525 Arg = Parens->getSubExpr();
1526 }
1527
1528 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg))
1529 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
1530 DRE = dyn_cast<QualifiedDeclRefExpr>(UnOp->getSubExpr());
1531
1532 if (!DRE)
1533 return Diag(Arg->getSourceRange().getBegin(),
1534 diag::err_template_arg_not_pointer_to_member_form)
1535 << Arg->getSourceRange();
1536
1537 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
1538 assert((isa<FieldDecl>(DRE->getDecl()) ||
1539 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
1540 "Only non-static member pointers can make it here");
1541
1542 // Okay: this is the address of a non-static member, and therefore
1543 // a member pointer constant.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001544 Member = DRE->getDecl();
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001545 return Invalid;
1546 }
1547
1548 // We found something else, but we don't know specifically what it is.
1549 Diag(Arg->getSourceRange().getBegin(),
1550 diag::err_template_arg_not_pointer_to_member_form)
1551 << Arg->getSourceRange();
1552 Diag(DRE->getDecl()->getLocation(),
1553 diag::note_template_arg_refers_here);
1554 return true;
1555}
1556
Douglas Gregorc15cb382009-02-09 23:23:08 +00001557/// \brief Check a template argument against its corresponding
1558/// non-type template parameter.
1559///
Douglas Gregor2943aed2009-03-03 04:44:36 +00001560/// This routine implements the semantics of C++ [temp.arg.nontype].
1561/// It returns true if an error occurred, and false otherwise. \p
1562/// InstantiatedParamType is the type of the non-type template
1563/// parameter after it has been instantiated.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001564///
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001565/// If no error was detected, Converted receives the converted template argument.
Douglas Gregorc15cb382009-02-09 23:23:08 +00001566bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Douglas Gregor2943aed2009-03-03 04:44:36 +00001567 QualType InstantiatedParamType, Expr *&Arg,
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001568 TemplateArgument &Converted) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00001569 SourceLocation StartLoc = Arg->getSourceRange().getBegin();
1570
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001571 // If either the parameter has a dependent type or the argument is
1572 // type-dependent, there's nothing we can check now.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001573 // FIXME: Add template argument to Converted!
Douglas Gregor40808ce2009-03-09 23:48:35 +00001574 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
1575 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001576 Converted = TemplateArgument(Arg);
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001577 return false;
Douglas Gregor40808ce2009-03-09 23:48:35 +00001578 }
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001579
1580 // C++ [temp.arg.nontype]p5:
1581 // The following conversions are performed on each expression used
1582 // as a non-type template-argument. If a non-type
1583 // template-argument cannot be converted to the type of the
1584 // corresponding template-parameter then the program is
1585 // ill-formed.
1586 //
1587 // -- for a non-type template-parameter of integral or
1588 // enumeration type, integral promotions (4.5) and integral
1589 // conversions (4.7) are applied.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001590 QualType ParamType = InstantiatedParamType;
Douglas Gregora35284b2009-02-11 00:19:33 +00001591 QualType ArgType = Arg->getType();
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001592 if (ParamType->isIntegralType() || ParamType->isEnumeralType()) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001593 // C++ [temp.arg.nontype]p1:
1594 // A template-argument for a non-type, non-template
1595 // template-parameter shall be one of:
1596 //
1597 // -- an integral constant-expression of integral or enumeration
1598 // type; or
1599 // -- the name of a non-type template-parameter; or
1600 SourceLocation NonConstantLoc;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001601 llvm::APSInt Value;
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001602 if (!ArgType->isIntegralType() && !ArgType->isEnumeralType()) {
1603 Diag(Arg->getSourceRange().getBegin(),
1604 diag::err_template_arg_not_integral_or_enumeral)
1605 << ArgType << Arg->getSourceRange();
1606 Diag(Param->getLocation(), diag::note_template_param_here);
1607 return true;
1608 } else if (!Arg->isValueDependent() &&
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001609 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001610 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
1611 << ArgType << Arg->getSourceRange();
1612 return true;
1613 }
1614
1615 // FIXME: We need some way to more easily get the unqualified form
1616 // of the types without going all the way to the
1617 // canonical type.
1618 if (Context.getCanonicalType(ParamType).getCVRQualifiers())
1619 ParamType = Context.getCanonicalType(ParamType).getUnqualifiedType();
1620 if (Context.getCanonicalType(ArgType).getCVRQualifiers())
1621 ArgType = Context.getCanonicalType(ArgType).getUnqualifiedType();
1622
1623 // Try to convert the argument to the parameter's type.
1624 if (ParamType == ArgType) {
1625 // Okay: no conversion necessary
1626 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
1627 !ParamType->isEnumeralType()) {
1628 // This is an integral promotion or conversion.
1629 ImpCastExprToType(Arg, ParamType);
1630 } else {
1631 // 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 Gregor6ae5e662009-02-10 23:36:10 +00001635 Diag(Param->getLocation(), diag::note_template_param_here);
1636 return true;
1637 }
1638
Douglas Gregorf80a9d52009-03-14 00:20:21 +00001639 QualType IntegerType = Context.getCanonicalType(ParamType);
1640 if (const EnumType *Enum = IntegerType->getAsEnumType())
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001641 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregorf80a9d52009-03-14 00:20:21 +00001642
1643 if (!Arg->isValueDependent()) {
1644 // Check that an unsigned parameter does not receive a negative
1645 // value.
1646 if (IntegerType->isUnsignedIntegerType()
1647 && (Value.isSigned() && Value.isNegative())) {
1648 Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_negative)
1649 << Value.toString(10) << Param->getType()
1650 << Arg->getSourceRange();
1651 Diag(Param->getLocation(), diag::note_template_param_here);
1652 return true;
1653 }
1654
1655 // Check that we don't overflow the template parameter type.
1656 unsigned AllowedBits = Context.getTypeSize(IntegerType);
1657 if (Value.getActiveBits() > AllowedBits) {
1658 Diag(Arg->getSourceRange().getBegin(),
1659 diag::err_template_arg_too_large)
1660 << Value.toString(10) << Param->getType()
1661 << Arg->getSourceRange();
1662 Diag(Param->getLocation(), diag::note_template_param_here);
1663 return true;
1664 }
1665
1666 if (Value.getBitWidth() != AllowedBits)
1667 Value.extOrTrunc(AllowedBits);
1668 Value.setIsSigned(IntegerType->isSignedIntegerType());
1669 }
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001670
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001671 // Add the value of this argument to the list of converted
1672 // arguments. We use the bitwidth and signedness of the template
1673 // parameter.
1674 if (Arg->isValueDependent()) {
1675 // The argument is value-dependent. Create a new
1676 // TemplateArgument with the converted expression.
1677 Converted = TemplateArgument(Arg);
1678 return false;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001679 }
1680
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001681 Converted = TemplateArgument(StartLoc, Value,
1682 ParamType->isEnumeralType() ? ParamType
1683 : IntegerType);
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001684 return false;
1685 }
Douglas Gregora35284b2009-02-11 00:19:33 +00001686
Douglas Gregorb86b0572009-02-11 01:18:59 +00001687 // Handle pointer-to-function, reference-to-function, and
1688 // pointer-to-member-function all in (roughly) the same way.
1689 if (// -- For a non-type template-parameter of type pointer to
1690 // function, only the function-to-pointer conversion (4.3) is
1691 // applied. If the template-argument represents a set of
1692 // overloaded functions (or a pointer to such), the matching
1693 // function is selected from the set (13.4).
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001694 // In C++0x, any std::nullptr_t value can be converted.
Douglas Gregorb86b0572009-02-11 01:18:59 +00001695 (ParamType->isPointerType() &&
Ted Kremenek35366a62009-07-17 17:50:17 +00001696 ParamType->getAsPointerType()->getPointeeType()->isFunctionType()) ||
Douglas Gregorb86b0572009-02-11 01:18:59 +00001697 // -- For a non-type template-parameter of type reference to
1698 // function, no conversions apply. If the template-argument
1699 // represents a set of overloaded functions, the matching
1700 // function is selected from the set (13.4).
1701 (ParamType->isReferenceType() &&
Ted Kremenek35366a62009-07-17 17:50:17 +00001702 ParamType->getAsReferenceType()->getPointeeType()->isFunctionType()) ||
Douglas Gregorb86b0572009-02-11 01:18:59 +00001703 // -- For a non-type template-parameter of type pointer to
1704 // member function, no conversions apply. If the
1705 // template-argument represents a set of overloaded member
1706 // functions, the matching member function is selected from
1707 // the set (13.4).
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001708 // Again, C++0x allows a std::nullptr_t value.
Douglas Gregorb86b0572009-02-11 01:18:59 +00001709 (ParamType->isMemberPointerType() &&
Ted Kremenek35366a62009-07-17 17:50:17 +00001710 ParamType->getAsMemberPointerType()->getPointeeType()
Douglas Gregorb86b0572009-02-11 01:18:59 +00001711 ->isFunctionType())) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001712 if (Context.hasSameUnqualifiedType(ArgType,
1713 ParamType.getNonReferenceType())) {
Douglas Gregora35284b2009-02-11 00:19:33 +00001714 // We don't have to do anything: the types already match.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001715 } else if (ArgType->isNullPtrType() && (ParamType->isPointerType() ||
1716 ParamType->isMemberPointerType())) {
1717 ArgType = ParamType;
1718 ImpCastExprToType(Arg, ParamType);
Douglas Gregorb86b0572009-02-11 01:18:59 +00001719 } else if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregora35284b2009-02-11 00:19:33 +00001720 ArgType = Context.getPointerType(ArgType);
1721 ImpCastExprToType(Arg, ArgType);
1722 } else if (FunctionDecl *Fn
1723 = ResolveAddressOfOverloadedFunction(Arg, ParamType, true)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001724 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
1725 return true;
1726
Douglas Gregora35284b2009-02-11 00:19:33 +00001727 FixOverloadedFunctionReference(Arg, Fn);
1728 ArgType = Arg->getType();
Douglas Gregorb86b0572009-02-11 01:18:59 +00001729 if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregora35284b2009-02-11 00:19:33 +00001730 ArgType = Context.getPointerType(Arg->getType());
1731 ImpCastExprToType(Arg, ArgType);
1732 }
1733 }
1734
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001735 if (!Context.hasSameUnqualifiedType(ArgType,
1736 ParamType.getNonReferenceType())) {
Douglas Gregora35284b2009-02-11 00:19:33 +00001737 // We can't perform this conversion.
1738 Diag(Arg->getSourceRange().getBegin(),
1739 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00001740 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregora35284b2009-02-11 00:19:33 +00001741 Diag(Param->getLocation(), diag::note_template_param_here);
1742 return true;
1743 }
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001744
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001745 if (ParamType->isMemberPointerType()) {
1746 NamedDecl *Member = 0;
1747 if (CheckTemplateArgumentPointerToMember(Arg, Member))
1748 return true;
1749
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00001750 if (Member)
1751 Member = cast<NamedDecl>(Member->getCanonicalDecl());
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001752 Converted = TemplateArgument(StartLoc, Member);
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001753 return false;
1754 }
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001755
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001756 NamedDecl *Entity = 0;
1757 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1758 return true;
1759
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00001760 if (Entity)
1761 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001762 Converted = TemplateArgument(StartLoc, Entity);
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001763 return false;
Douglas Gregora35284b2009-02-11 00:19:33 +00001764 }
1765
Chris Lattnerfe90de72009-02-20 21:37:53 +00001766 if (ParamType->isPointerType()) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00001767 // -- for a non-type template-parameter of type pointer to
1768 // object, qualification conversions (4.4) and the
1769 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001770 // C++0x also allows a value of std::nullptr_t.
Ted Kremenek35366a62009-07-17 17:50:17 +00001771 assert(ParamType->getAsPointerType()->getPointeeType()->isObjectType() &&
Douglas Gregorb86b0572009-02-11 01:18:59 +00001772 "Only object pointers allowed here");
Douglas Gregorf684e6e2009-02-11 00:44:29 +00001773
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001774 if (ArgType->isNullPtrType()) {
1775 ArgType = ParamType;
1776 ImpCastExprToType(Arg, ParamType);
1777 } else if (ArgType->isArrayType()) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00001778 ArgType = Context.getArrayDecayedType(ArgType);
1779 ImpCastExprToType(Arg, ArgType);
Douglas Gregorf684e6e2009-02-11 00:44:29 +00001780 }
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001781
Douglas Gregorb86b0572009-02-11 01:18:59 +00001782 if (IsQualificationConversion(ArgType, ParamType)) {
1783 ArgType = ParamType;
1784 ImpCastExprToType(Arg, ParamType);
1785 }
1786
Douglas Gregor8e6563b2009-02-11 18:22:40 +00001787 if (!Context.hasSameUnqualifiedType(ArgType, ParamType)) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00001788 // We can't perform this conversion.
1789 Diag(Arg->getSourceRange().getBegin(),
1790 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00001791 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregorb86b0572009-02-11 01:18:59 +00001792 Diag(Param->getLocation(), diag::note_template_param_here);
1793 return true;
1794 }
1795
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001796 NamedDecl *Entity = 0;
1797 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1798 return true;
1799
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00001800 if (Entity)
1801 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001802 Converted = TemplateArgument(StartLoc, Entity);
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001803 return false;
Douglas Gregorf684e6e2009-02-11 00:44:29 +00001804 }
Douglas Gregorb86b0572009-02-11 01:18:59 +00001805
Ted Kremenek35366a62009-07-17 17:50:17 +00001806 if (const ReferenceType *ParamRefType = ParamType->getAsReferenceType()) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00001807 // -- For a non-type template-parameter of type reference to
1808 // object, no conversions apply. The type referred to by the
1809 // reference may be more cv-qualified than the (otherwise
1810 // identical) type of the template-argument. The
1811 // template-parameter is bound directly to the
1812 // template-argument, which must be an lvalue.
Douglas Gregorbad0e652009-03-24 20:32:41 +00001813 assert(ParamRefType->getPointeeType()->isObjectType() &&
Douglas Gregorb86b0572009-02-11 01:18:59 +00001814 "Only object references allowed here");
Douglas Gregorf684e6e2009-02-11 00:44:29 +00001815
Douglas Gregor8e6563b2009-02-11 18:22:40 +00001816 if (!Context.hasSameUnqualifiedType(ParamRefType->getPointeeType(), ArgType)) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00001817 Diag(Arg->getSourceRange().getBegin(),
1818 diag::err_template_arg_no_ref_bind)
Douglas Gregor2943aed2009-03-03 04:44:36 +00001819 << InstantiatedParamType << Arg->getType()
Douglas Gregorb86b0572009-02-11 01:18:59 +00001820 << Arg->getSourceRange();
1821 Diag(Param->getLocation(), diag::note_template_param_here);
1822 return true;
1823 }
1824
1825 unsigned ParamQuals
1826 = Context.getCanonicalType(ParamType).getCVRQualifiers();
1827 unsigned ArgQuals = Context.getCanonicalType(ArgType).getCVRQualifiers();
1828
1829 if ((ParamQuals | ArgQuals) != ParamQuals) {
1830 Diag(Arg->getSourceRange().getBegin(),
1831 diag::err_template_arg_ref_bind_ignores_quals)
Douglas Gregor2943aed2009-03-03 04:44:36 +00001832 << InstantiatedParamType << Arg->getType()
Douglas Gregorb86b0572009-02-11 01:18:59 +00001833 << Arg->getSourceRange();
1834 Diag(Param->getLocation(), diag::note_template_param_here);
1835 return true;
1836 }
1837
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001838 NamedDecl *Entity = 0;
1839 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1840 return true;
1841
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00001842 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001843 Converted = TemplateArgument(StartLoc, Entity);
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001844 return false;
Douglas Gregorb86b0572009-02-11 01:18:59 +00001845 }
Douglas Gregor658bbb52009-02-11 16:16:59 +00001846
1847 // -- For a non-type template-parameter of type pointer to data
1848 // member, qualification conversions (4.4) are applied.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001849 // C++0x allows std::nullptr_t values.
Douglas Gregor658bbb52009-02-11 16:16:59 +00001850 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
1851
Douglas Gregor8e6563b2009-02-11 18:22:40 +00001852 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
Douglas Gregor658bbb52009-02-11 16:16:59 +00001853 // Types match exactly: nothing more to do here.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001854 } else if (ArgType->isNullPtrType()) {
1855 ImpCastExprToType(Arg, ParamType);
Douglas Gregor658bbb52009-02-11 16:16:59 +00001856 } else if (IsQualificationConversion(ArgType, ParamType)) {
1857 ImpCastExprToType(Arg, ParamType);
1858 } else {
1859 // We can't perform this conversion.
1860 Diag(Arg->getSourceRange().getBegin(),
1861 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00001862 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor658bbb52009-02-11 16:16:59 +00001863 Diag(Param->getLocation(), diag::note_template_param_here);
1864 return true;
1865 }
1866
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001867 NamedDecl *Member = 0;
1868 if (CheckTemplateArgumentPointerToMember(Arg, Member))
1869 return true;
1870
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00001871 if (Member)
1872 Member = cast<NamedDecl>(Member->getCanonicalDecl());
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001873 Converted = TemplateArgument(StartLoc, Member);
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001874 return false;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001875}
1876
1877/// \brief Check a template argument against its corresponding
1878/// template template parameter.
1879///
1880/// This routine implements the semantics of C++ [temp.arg.template].
1881/// It returns true if an error occurred, and false otherwise.
1882bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
1883 DeclRefExpr *Arg) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00001884 assert(isa<TemplateDecl>(Arg->getDecl()) && "Only template decls allowed");
1885 TemplateDecl *Template = cast<TemplateDecl>(Arg->getDecl());
1886
1887 // C++ [temp.arg.template]p1:
1888 // A template-argument for a template template-parameter shall be
1889 // the name of a class template, expressed as id-expression. Only
1890 // primary class templates are considered when matching the
1891 // template template argument with the corresponding parameter;
1892 // partial specializations are not considered even if their
1893 // parameter lists match that of the template template parameter.
Douglas Gregorba1ecb52009-06-12 19:43:02 +00001894 //
1895 // Note that we also allow template template parameters here, which
1896 // will happen when we are dealing with, e.g., class template
1897 // partial specializations.
1898 if (!isa<ClassTemplateDecl>(Template) &&
1899 !isa<TemplateTemplateParmDecl>(Template)) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00001900 assert(isa<FunctionTemplateDecl>(Template) &&
1901 "Only function templates are possible here");
Douglas Gregore53060f2009-06-25 22:08:12 +00001902 Diag(Arg->getLocStart(), diag::err_template_arg_not_class_template);
1903 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
Douglas Gregordd0574e2009-02-10 00:24:35 +00001904 << Template;
1905 }
1906
1907 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
1908 Param->getTemplateParameters(),
1909 true, true,
1910 Arg->getSourceRange().getBegin());
Douglas Gregorc15cb382009-02-09 23:23:08 +00001911}
1912
Douglas Gregorddc29e12009-02-06 22:42:48 +00001913/// \brief Determine whether the given template parameter lists are
1914/// equivalent.
1915///
1916/// \param New The new template parameter list, typically written in the
1917/// source code as part of a new template declaration.
1918///
1919/// \param Old The old template parameter list, typically found via
1920/// name lookup of the template declared with this template parameter
1921/// list.
1922///
1923/// \param Complain If true, this routine will produce a diagnostic if
1924/// the template parameter lists are not equivalent.
1925///
Douglas Gregordd0574e2009-02-10 00:24:35 +00001926/// \param IsTemplateTemplateParm If true, this routine is being
1927/// called to compare the template parameter lists of a template
1928/// template parameter.
1929///
1930/// \param TemplateArgLoc If this source location is valid, then we
1931/// are actually checking the template parameter list of a template
1932/// argument (New) against the template parameter list of its
1933/// corresponding template template parameter (Old). We produce
1934/// slightly different diagnostics in this scenario.
1935///
Douglas Gregorddc29e12009-02-06 22:42:48 +00001936/// \returns True if the template parameter lists are equal, false
1937/// otherwise.
1938bool
1939Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
1940 TemplateParameterList *Old,
1941 bool Complain,
Douglas Gregordd0574e2009-02-10 00:24:35 +00001942 bool IsTemplateTemplateParm,
1943 SourceLocation TemplateArgLoc) {
Douglas Gregorddc29e12009-02-06 22:42:48 +00001944 if (Old->size() != New->size()) {
1945 if (Complain) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00001946 unsigned NextDiag = diag::err_template_param_list_different_arity;
1947 if (TemplateArgLoc.isValid()) {
1948 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
1949 NextDiag = diag::note_template_param_list_different_arity;
1950 }
1951 Diag(New->getTemplateLoc(), NextDiag)
1952 << (New->size() > Old->size())
1953 << IsTemplateTemplateParm
1954 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
Douglas Gregorddc29e12009-02-06 22:42:48 +00001955 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
1956 << IsTemplateTemplateParm
1957 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
1958 }
1959
1960 return false;
1961 }
1962
1963 for (TemplateParameterList::iterator OldParm = Old->begin(),
1964 OldParmEnd = Old->end(), NewParm = New->begin();
1965 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
1966 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
Douglas Gregor34d1dc92009-06-24 16:50:40 +00001967 if (Complain) {
1968 unsigned NextDiag = diag::err_template_param_different_kind;
1969 if (TemplateArgLoc.isValid()) {
1970 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
1971 NextDiag = diag::note_template_param_different_kind;
1972 }
1973 Diag((*NewParm)->getLocation(), NextDiag)
1974 << IsTemplateTemplateParm;
1975 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
1976 << IsTemplateTemplateParm;
Douglas Gregordd0574e2009-02-10 00:24:35 +00001977 }
Douglas Gregorddc29e12009-02-06 22:42:48 +00001978 return false;
1979 }
1980
1981 if (isa<TemplateTypeParmDecl>(*OldParm)) {
1982 // Okay; all template type parameters are equivalent (since we
Douglas Gregordd0574e2009-02-10 00:24:35 +00001983 // know we're at the same index).
1984#if 0
Mike Stump390b4cc2009-05-16 07:39:55 +00001985 // FIXME: Enable this code in debug mode *after* we properly go through
1986 // and "instantiate" the template parameter lists of template template
1987 // parameters. It's only after this instantiation that (1) any dependent
1988 // types within the template parameter list of the template template
1989 // parameter can be checked, and (2) the template type parameter depths
Douglas Gregordd0574e2009-02-10 00:24:35 +00001990 // will match up.
Douglas Gregorddc29e12009-02-06 22:42:48 +00001991 QualType OldParmType
1992 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*OldParm));
1993 QualType NewParmType
1994 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*NewParm));
1995 assert(Context.getCanonicalType(OldParmType) ==
1996 Context.getCanonicalType(NewParmType) &&
1997 "type parameter mismatch?");
1998#endif
1999 } else if (NonTypeTemplateParmDecl *OldNTTP
2000 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
2001 // The types of non-type template parameters must agree.
2002 NonTypeTemplateParmDecl *NewNTTP
2003 = cast<NonTypeTemplateParmDecl>(*NewParm);
2004 if (Context.getCanonicalType(OldNTTP->getType()) !=
2005 Context.getCanonicalType(NewNTTP->getType())) {
2006 if (Complain) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00002007 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
2008 if (TemplateArgLoc.isValid()) {
2009 Diag(TemplateArgLoc,
2010 diag::err_template_arg_template_params_mismatch);
2011 NextDiag = diag::note_template_nontype_parm_different_type;
2012 }
2013 Diag(NewNTTP->getLocation(), NextDiag)
Douglas Gregorddc29e12009-02-06 22:42:48 +00002014 << NewNTTP->getType()
2015 << IsTemplateTemplateParm;
2016 Diag(OldNTTP->getLocation(),
2017 diag::note_template_nontype_parm_prev_declaration)
2018 << OldNTTP->getType();
2019 }
2020 return false;
2021 }
2022 } else {
2023 // The template parameter lists of template template
2024 // parameters must agree.
2025 // FIXME: Could we perform a faster "type" comparison here?
2026 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
2027 "Only template template parameters handled here");
2028 TemplateTemplateParmDecl *OldTTP
2029 = cast<TemplateTemplateParmDecl>(*OldParm);
2030 TemplateTemplateParmDecl *NewTTP
2031 = cast<TemplateTemplateParmDecl>(*NewParm);
2032 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
2033 OldTTP->getTemplateParameters(),
2034 Complain,
Douglas Gregordd0574e2009-02-10 00:24:35 +00002035 /*IsTemplateTemplateParm=*/true,
2036 TemplateArgLoc))
Douglas Gregorddc29e12009-02-06 22:42:48 +00002037 return false;
2038 }
2039 }
2040
2041 return true;
2042}
2043
2044/// \brief Check whether a template can be declared within this scope.
2045///
2046/// If the template declaration is valid in this scope, returns
2047/// false. Otherwise, issues a diagnostic and returns true.
2048bool
2049Sema::CheckTemplateDeclScope(Scope *S,
2050 MultiTemplateParamsArg &TemplateParameterLists) {
2051 assert(TemplateParameterLists.size() > 0 && "Not a template");
2052
2053 // Find the nearest enclosing declaration scope.
2054 while ((S->getFlags() & Scope::DeclScope) == 0 ||
2055 (S->getFlags() & Scope::TemplateParamScope) != 0)
2056 S = S->getParent();
2057
2058 TemplateParameterList *TemplateParams =
2059 static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
2060 SourceLocation TemplateLoc = TemplateParams->getTemplateLoc();
2061 SourceRange TemplateRange
2062 = SourceRange(TemplateLoc, TemplateParams->getRAngleLoc());
2063
2064 // C++ [temp]p2:
2065 // A template-declaration can appear only as a namespace scope or
2066 // class scope declaration.
2067 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
2068 while (Ctx && isa<LinkageSpecDecl>(Ctx)) {
2069 if (cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
2070 return Diag(TemplateLoc, diag::err_template_linkage)
2071 << TemplateRange;
2072
2073 Ctx = Ctx->getParent();
2074 }
2075
2076 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
2077 return false;
2078
2079 return Diag(TemplateLoc, diag::err_template_outside_namespace_or_class_scope)
2080 << TemplateRange;
2081}
Douglas Gregorcc636682009-02-17 23:15:12 +00002082
Douglas Gregorff668032009-05-13 18:28:20 +00002083/// \brief Check whether a class template specialization or explicit
2084/// instantiation in the current context is well-formed.
Douglas Gregor88b70942009-02-25 22:02:03 +00002085///
Douglas Gregorff668032009-05-13 18:28:20 +00002086/// This routine determines whether a class template specialization or
2087/// explicit instantiation can be declared in the current context
2088/// (C++ [temp.expl.spec]p2, C++0x [temp.explicit]p2) and emits
2089/// appropriate diagnostics if there was an error. It returns true if
2090// there was an error that we cannot recover from, and false otherwise.
Douglas Gregor88b70942009-02-25 22:02:03 +00002091bool
2092Sema::CheckClassTemplateSpecializationScope(ClassTemplateDecl *ClassTemplate,
2093 ClassTemplateSpecializationDecl *PrevDecl,
2094 SourceLocation TemplateNameLoc,
Douglas Gregorff668032009-05-13 18:28:20 +00002095 SourceRange ScopeSpecifierRange,
Douglas Gregor16df8502009-06-12 22:21:45 +00002096 bool PartialSpecialization,
Douglas Gregorff668032009-05-13 18:28:20 +00002097 bool ExplicitInstantiation) {
Douglas Gregor88b70942009-02-25 22:02:03 +00002098 // C++ [temp.expl.spec]p2:
2099 // An explicit specialization shall be declared in the namespace
2100 // of which the template is a member, or, for member templates, in
2101 // the namespace of which the enclosing class or enclosing class
2102 // template is a member. An explicit specialization of a member
2103 // function, member class or static data member of a class
2104 // template shall be declared in the namespace of which the class
2105 // template is a member. Such a declaration may also be a
2106 // definition. If the declaration is not a definition, the
2107 // specialization may be defined later in the name- space in which
2108 // the explicit specialization was declared, or in a namespace
2109 // that encloses the one in which the explicit specialization was
2110 // declared.
2111 if (CurContext->getLookupContext()->isFunctionOrMethod()) {
Douglas Gregor16df8502009-06-12 22:21:45 +00002112 int Kind = ExplicitInstantiation? 2 : PartialSpecialization? 1 : 0;
Douglas Gregor88b70942009-02-25 22:02:03 +00002113 Diag(TemplateNameLoc, diag::err_template_spec_decl_function_scope)
Douglas Gregor16df8502009-06-12 22:21:45 +00002114 << Kind << ClassTemplate;
Douglas Gregor88b70942009-02-25 22:02:03 +00002115 return true;
2116 }
2117
2118 DeclContext *DC = CurContext->getEnclosingNamespaceContext();
2119 DeclContext *TemplateContext
2120 = ClassTemplate->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregorff668032009-05-13 18:28:20 +00002121 if ((!PrevDecl || PrevDecl->getSpecializationKind() == TSK_Undeclared) &&
2122 !ExplicitInstantiation) {
Douglas Gregor88b70942009-02-25 22:02:03 +00002123 // There is no prior declaration of this entity, so this
2124 // specialization must be in the same context as the template
2125 // itself.
2126 if (DC != TemplateContext) {
2127 if (isa<TranslationUnitDecl>(TemplateContext))
2128 Diag(TemplateNameLoc, diag::err_template_spec_decl_out_of_scope_global)
Douglas Gregor16df8502009-06-12 22:21:45 +00002129 << PartialSpecialization
Douglas Gregor88b70942009-02-25 22:02:03 +00002130 << ClassTemplate << ScopeSpecifierRange;
2131 else if (isa<NamespaceDecl>(TemplateContext))
2132 Diag(TemplateNameLoc, diag::err_template_spec_decl_out_of_scope)
Douglas Gregor16df8502009-06-12 22:21:45 +00002133 << PartialSpecialization << ClassTemplate
2134 << cast<NamedDecl>(TemplateContext) << ScopeSpecifierRange;
Douglas Gregor88b70942009-02-25 22:02:03 +00002135
2136 Diag(ClassTemplate->getLocation(), diag::note_template_decl_here);
2137 }
2138
2139 return false;
2140 }
2141
2142 // We have a previous declaration of this entity. Make sure that
2143 // this redeclaration (or definition) occurs in an enclosing namespace.
2144 if (!CurContext->Encloses(TemplateContext)) {
Mike Stump390b4cc2009-05-16 07:39:55 +00002145 // FIXME: In C++98, we would like to turn these errors into warnings,
2146 // dependent on a -Wc++0x flag.
Douglas Gregorff668032009-05-13 18:28:20 +00002147 bool SuppressedDiag = false;
Douglas Gregor16df8502009-06-12 22:21:45 +00002148 int Kind = ExplicitInstantiation? 2 : PartialSpecialization? 1 : 0;
Douglas Gregorff668032009-05-13 18:28:20 +00002149 if (isa<TranslationUnitDecl>(TemplateContext)) {
2150 if (!ExplicitInstantiation || getLangOptions().CPlusPlus0x)
2151 Diag(TemplateNameLoc, diag::err_template_spec_redecl_global_scope)
Douglas Gregor16df8502009-06-12 22:21:45 +00002152 << Kind << ClassTemplate << ScopeSpecifierRange;
Douglas Gregorff668032009-05-13 18:28:20 +00002153 else
2154 SuppressedDiag = true;
2155 } else if (isa<NamespaceDecl>(TemplateContext)) {
2156 if (!ExplicitInstantiation || getLangOptions().CPlusPlus0x)
2157 Diag(TemplateNameLoc, diag::err_template_spec_redecl_out_of_scope)
Douglas Gregor16df8502009-06-12 22:21:45 +00002158 << Kind << ClassTemplate
Douglas Gregorff668032009-05-13 18:28:20 +00002159 << cast<NamedDecl>(TemplateContext) << ScopeSpecifierRange;
2160 else
2161 SuppressedDiag = true;
2162 }
Douglas Gregor88b70942009-02-25 22:02:03 +00002163
Douglas Gregorff668032009-05-13 18:28:20 +00002164 if (!SuppressedDiag)
2165 Diag(ClassTemplate->getLocation(), diag::note_template_decl_here);
Douglas Gregor88b70942009-02-25 22:02:03 +00002166 }
2167
2168 return false;
2169}
2170
Douglas Gregore94866f2009-06-12 21:21:02 +00002171/// \brief Check the non-type template arguments of a class template
2172/// partial specialization according to C++ [temp.class.spec]p9.
2173///
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002174/// \param TemplateParams the template parameters of the primary class
2175/// template.
2176///
2177/// \param TemplateArg the template arguments of the class template
2178/// partial specialization.
2179///
2180/// \param MirrorsPrimaryTemplate will be set true if the class
2181/// template partial specialization arguments are identical to the
2182/// implicit template arguments of the primary template. This is not
2183/// necessarily an error (C++0x), and it is left to the caller to diagnose
2184/// this condition when it is an error.
2185///
Douglas Gregore94866f2009-06-12 21:21:02 +00002186/// \returns true if there was an error, false otherwise.
2187bool Sema::CheckClassTemplatePartialSpecializationArgs(
2188 TemplateParameterList *TemplateParams,
Anders Carlsson6360be72009-06-13 18:20:51 +00002189 const TemplateArgumentListBuilder &TemplateArgs,
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002190 bool &MirrorsPrimaryTemplate) {
Douglas Gregore94866f2009-06-12 21:21:02 +00002191 // FIXME: the interface to this function will have to change to
2192 // accommodate variadic templates.
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002193 MirrorsPrimaryTemplate = true;
Anders Carlsson6360be72009-06-13 18:20:51 +00002194
Anders Carlssonfb250522009-06-23 01:26:57 +00002195 const TemplateArgument *ArgList = TemplateArgs.getFlatArguments();
Anders Carlsson6360be72009-06-13 18:20:51 +00002196
Douglas Gregore94866f2009-06-12 21:21:02 +00002197 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002198 // Determine whether the template argument list of the partial
2199 // specialization is identical to the implicit argument list of
2200 // the primary template. The caller may need to diagnostic this as
2201 // an error per C++ [temp.class.spec]p9b3.
2202 if (MirrorsPrimaryTemplate) {
2203 if (TemplateTypeParmDecl *TTP
2204 = dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(I))) {
2205 if (Context.getCanonicalType(Context.getTypeDeclType(TTP)) !=
Anders Carlsson6360be72009-06-13 18:20:51 +00002206 Context.getCanonicalType(ArgList[I].getAsType()))
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002207 MirrorsPrimaryTemplate = false;
2208 } else if (TemplateTemplateParmDecl *TTP
2209 = dyn_cast<TemplateTemplateParmDecl>(
2210 TemplateParams->getParam(I))) {
2211 // FIXME: We should settle on either Declaration storage or
2212 // Expression storage for template template parameters.
2213 TemplateTemplateParmDecl *ArgDecl
2214 = dyn_cast_or_null<TemplateTemplateParmDecl>(
Anders Carlsson6360be72009-06-13 18:20:51 +00002215 ArgList[I].getAsDecl());
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002216 if (!ArgDecl)
2217 if (DeclRefExpr *DRE
Anders Carlsson6360be72009-06-13 18:20:51 +00002218 = dyn_cast_or_null<DeclRefExpr>(ArgList[I].getAsExpr()))
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002219 ArgDecl = dyn_cast<TemplateTemplateParmDecl>(DRE->getDecl());
2220
2221 if (!ArgDecl ||
2222 ArgDecl->getIndex() != TTP->getIndex() ||
2223 ArgDecl->getDepth() != TTP->getDepth())
2224 MirrorsPrimaryTemplate = false;
2225 }
2226 }
2227
Douglas Gregore94866f2009-06-12 21:21:02 +00002228 NonTypeTemplateParmDecl *Param
2229 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002230 if (!Param) {
Douglas Gregore94866f2009-06-12 21:21:02 +00002231 continue;
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002232 }
2233
Anders Carlsson6360be72009-06-13 18:20:51 +00002234 Expr *ArgExpr = ArgList[I].getAsExpr();
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002235 if (!ArgExpr) {
2236 MirrorsPrimaryTemplate = false;
Douglas Gregore94866f2009-06-12 21:21:02 +00002237 continue;
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002238 }
Douglas Gregore94866f2009-06-12 21:21:02 +00002239
2240 // C++ [temp.class.spec]p8:
2241 // A non-type argument is non-specialized if it is the name of a
2242 // non-type parameter. All other non-type arguments are
2243 // specialized.
2244 //
2245 // Below, we check the two conditions that only apply to
2246 // specialized non-type arguments, so skip any non-specialized
2247 // arguments.
2248 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002249 if (NonTypeTemplateParmDecl *NTTP
2250 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl())) {
2251 if (MirrorsPrimaryTemplate &&
2252 (Param->getIndex() != NTTP->getIndex() ||
2253 Param->getDepth() != NTTP->getDepth()))
2254 MirrorsPrimaryTemplate = false;
2255
Douglas Gregore94866f2009-06-12 21:21:02 +00002256 continue;
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002257 }
Douglas Gregore94866f2009-06-12 21:21:02 +00002258
2259 // C++ [temp.class.spec]p9:
2260 // Within the argument list of a class template partial
2261 // specialization, the following restrictions apply:
2262 // -- A partially specialized non-type argument expression
2263 // shall not involve a template parameter of the partial
2264 // specialization except when the argument expression is a
2265 // simple identifier.
2266 if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
2267 Diag(ArgExpr->getLocStart(),
2268 diag::err_dependent_non_type_arg_in_partial_spec)
2269 << ArgExpr->getSourceRange();
2270 return true;
2271 }
2272
2273 // -- The type of a template parameter corresponding to a
2274 // specialized non-type argument shall not be dependent on a
2275 // parameter of the specialization.
2276 if (Param->getType()->isDependentType()) {
2277 Diag(ArgExpr->getLocStart(),
2278 diag::err_dependent_typed_non_type_arg_in_partial_spec)
2279 << Param->getType()
2280 << ArgExpr->getSourceRange();
2281 Diag(Param->getLocation(), diag::note_template_param_here);
2282 return true;
2283 }
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002284
2285 MirrorsPrimaryTemplate = false;
Douglas Gregore94866f2009-06-12 21:21:02 +00002286 }
2287
2288 return false;
2289}
2290
Douglas Gregor212e81c2009-03-25 00:13:59 +00002291Sema::DeclResult
Douglas Gregorcc636682009-02-17 23:15:12 +00002292Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec, TagKind TK,
2293 SourceLocation KWLoc,
2294 const CXXScopeSpec &SS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00002295 TemplateTy TemplateD,
Douglas Gregorcc636682009-02-17 23:15:12 +00002296 SourceLocation TemplateNameLoc,
2297 SourceLocation LAngleLoc,
Douglas Gregor40808ce2009-03-09 23:48:35 +00002298 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregorcc636682009-02-17 23:15:12 +00002299 SourceLocation *TemplateArgLocs,
2300 SourceLocation RAngleLoc,
2301 AttributeList *Attr,
2302 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregorcc636682009-02-17 23:15:12 +00002303 // Find the class template we're specializing
Douglas Gregor7532dc62009-03-30 22:58:21 +00002304 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Douglas Gregorcc636682009-02-17 23:15:12 +00002305 ClassTemplateDecl *ClassTemplate
Douglas Gregor7532dc62009-03-30 22:58:21 +00002306 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
Douglas Gregorcc636682009-02-17 23:15:12 +00002307
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002308 bool isPartialSpecialization = false;
2309
Douglas Gregor88b70942009-02-25 22:02:03 +00002310 // Check the validity of the template headers that introduce this
2311 // template.
Douglas Gregor6bc9f7e2009-02-25 22:18:32 +00002312 // FIXME: Once we have member templates, we'll need to check
2313 // C++ [temp.expl.spec]p17-18, where we could have multiple levels of
2314 // template<> headers.
Douglas Gregor4b2d3f72009-02-26 21:00:50 +00002315 if (TemplateParameterLists.size() == 0)
2316 Diag(KWLoc, diag::err_template_spec_needs_header)
Douglas Gregorb2fb6de2009-02-27 17:53:17 +00002317 << CodeModificationHint::CreateInsertion(KWLoc, "template<> ");
Douglas Gregor4b2d3f72009-02-26 21:00:50 +00002318 else {
Douglas Gregor88b70942009-02-25 22:02:03 +00002319 TemplateParameterList *TemplateParams
2320 = static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
Chris Lattnerb28317a2009-03-28 19:18:32 +00002321 if (TemplateParameterLists.size() > 1) {
2322 Diag(TemplateParams->getTemplateLoc(),
2323 diag::err_template_spec_extra_headers);
2324 return true;
2325 }
Douglas Gregor88b70942009-02-25 22:02:03 +00002326
Douglas Gregorba1ecb52009-06-12 19:43:02 +00002327 if (TemplateParams->size() > 0) {
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002328 isPartialSpecialization = true;
Douglas Gregorba1ecb52009-06-12 19:43:02 +00002329
2330 // C++ [temp.class.spec]p10:
2331 // The template parameter list of a specialization shall not
2332 // contain default template argument values.
2333 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
2334 Decl *Param = TemplateParams->getParam(I);
2335 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
2336 if (TTP->hasDefaultArgument()) {
2337 Diag(TTP->getDefaultArgumentLoc(),
2338 diag::err_default_arg_in_partial_spec);
2339 TTP->setDefaultArgument(QualType(), SourceLocation(), false);
2340 }
2341 } else if (NonTypeTemplateParmDecl *NTTP
2342 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2343 if (Expr *DefArg = NTTP->getDefaultArgument()) {
2344 Diag(NTTP->getDefaultArgumentLoc(),
2345 diag::err_default_arg_in_partial_spec)
2346 << DefArg->getSourceRange();
2347 NTTP->setDefaultArgument(0);
2348 DefArg->Destroy(Context);
2349 }
2350 } else {
2351 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
2352 if (Expr *DefArg = TTP->getDefaultArgument()) {
2353 Diag(TTP->getDefaultArgumentLoc(),
2354 diag::err_default_arg_in_partial_spec)
2355 << DefArg->getSourceRange();
2356 TTP->setDefaultArgument(0);
2357 DefArg->Destroy(Context);
2358 }
2359 }
2360 }
2361 }
Douglas Gregor88b70942009-02-25 22:02:03 +00002362 }
2363
Douglas Gregorcc636682009-02-17 23:15:12 +00002364 // Check that the specialization uses the same tag kind as the
2365 // original template.
2366 TagDecl::TagKind Kind;
2367 switch (TagSpec) {
2368 default: assert(0 && "Unknown tag type!");
2369 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2370 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2371 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2372 }
Douglas Gregor501c5ce2009-05-14 16:41:31 +00002373 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
2374 Kind, KWLoc,
2375 *ClassTemplate->getIdentifier())) {
Douglas Gregora3a83512009-04-01 23:51:29 +00002376 Diag(KWLoc, diag::err_use_with_wrong_tag)
2377 << ClassTemplate
2378 << CodeModificationHint::CreateReplacement(KWLoc,
2379 ClassTemplate->getTemplatedDecl()->getKindName());
Douglas Gregorcc636682009-02-17 23:15:12 +00002380 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
2381 diag::note_previous_use);
2382 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
2383 }
2384
Douglas Gregor40808ce2009-03-09 23:48:35 +00002385 // Translate the parser's template argument list in our AST format.
2386 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
2387 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
2388
Douglas Gregorcc636682009-02-17 23:15:12 +00002389 // Check that the template argument list is well-formed for this
2390 // template.
Anders Carlssonfb250522009-06-23 01:26:57 +00002391 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
2392 TemplateArgs.size());
Douglas Gregorcc636682009-02-17 23:15:12 +00002393 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
Anders Carlsson6360be72009-06-13 18:20:51 +00002394 TemplateArgs.data(), TemplateArgs.size(),
Douglas Gregor16134c62009-07-01 00:28:38 +00002395 RAngleLoc, false, Converted))
Douglas Gregor212e81c2009-03-25 00:13:59 +00002396 return true;
Douglas Gregorcc636682009-02-17 23:15:12 +00002397
Anders Carlssonfb250522009-06-23 01:26:57 +00002398 assert((Converted.structuredSize() ==
Douglas Gregorcc636682009-02-17 23:15:12 +00002399 ClassTemplate->getTemplateParameters()->size()) &&
2400 "Converted template argument list is too short!");
2401
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002402 // Find the class template (partial) specialization declaration that
Douglas Gregorcc636682009-02-17 23:15:12 +00002403 // corresponds to these arguments.
2404 llvm::FoldingSetNodeID ID;
Douglas Gregorba1ecb52009-06-12 19:43:02 +00002405 if (isPartialSpecialization) {
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002406 bool MirrorsPrimaryTemplate;
Douglas Gregore94866f2009-06-12 21:21:02 +00002407 if (CheckClassTemplatePartialSpecializationArgs(
2408 ClassTemplate->getTemplateParameters(),
Anders Carlssonfb250522009-06-23 01:26:57 +00002409 Converted, MirrorsPrimaryTemplate))
Douglas Gregore94866f2009-06-12 21:21:02 +00002410 return true;
2411
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002412 if (MirrorsPrimaryTemplate) {
2413 // C++ [temp.class.spec]p9b3:
2414 //
2415 // -- The argument list of the specialization shall not be identical
2416 // to the implicit argument list of the primary template.
2417 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
2418 << (TK == TK_Definition)
2419 << CodeModificationHint::CreateRemoval(SourceRange(LAngleLoc,
2420 RAngleLoc));
Douglas Gregorbd1099e2009-07-23 16:36:45 +00002421 return CheckClassTemplate(S, TagSpec, TK, KWLoc, SS,
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002422 ClassTemplate->getIdentifier(),
2423 TemplateNameLoc,
2424 Attr,
2425 move(TemplateParameterLists),
2426 AS_none);
2427 }
2428
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002429 // FIXME: Template parameter list matters, too
Anders Carlsson1c5976e2009-06-05 03:43:12 +00002430 ClassTemplatePartialSpecializationDecl::Profile(ID,
Anders Carlssonfb250522009-06-23 01:26:57 +00002431 Converted.getFlatArguments(),
Douglas Gregor828e2262009-07-29 16:09:57 +00002432 Converted.flatSize(),
2433 Context);
Douglas Gregorba1ecb52009-06-12 19:43:02 +00002434 }
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002435 else
Anders Carlsson1c5976e2009-06-05 03:43:12 +00002436 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlssonfb250522009-06-23 01:26:57 +00002437 Converted.getFlatArguments(),
Douglas Gregor828e2262009-07-29 16:09:57 +00002438 Converted.flatSize(),
2439 Context);
Douglas Gregorcc636682009-02-17 23:15:12 +00002440 void *InsertPos = 0;
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002441 ClassTemplateSpecializationDecl *PrevDecl = 0;
2442
2443 if (isPartialSpecialization)
2444 PrevDecl
2445 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
2446 InsertPos);
2447 else
2448 PrevDecl
2449 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorcc636682009-02-17 23:15:12 +00002450
2451 ClassTemplateSpecializationDecl *Specialization = 0;
2452
Douglas Gregor88b70942009-02-25 22:02:03 +00002453 // Check whether we can declare a class template specialization in
2454 // the current scope.
2455 if (CheckClassTemplateSpecializationScope(ClassTemplate, PrevDecl,
2456 TemplateNameLoc,
Douglas Gregorff668032009-05-13 18:28:20 +00002457 SS.getRange(),
Douglas Gregor16df8502009-06-12 22:21:45 +00002458 isPartialSpecialization,
Douglas Gregorff668032009-05-13 18:28:20 +00002459 /*ExplicitInstantiation=*/false))
Douglas Gregor212e81c2009-03-25 00:13:59 +00002460 return true;
Douglas Gregor88b70942009-02-25 22:02:03 +00002461
Douglas Gregorcc636682009-02-17 23:15:12 +00002462 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
2463 // Since the only prior class template specialization with these
2464 // arguments was referenced but not declared, reuse that
2465 // declaration node as our own, updating its source location to
2466 // reflect our new declaration.
Douglas Gregorcc636682009-02-17 23:15:12 +00002467 Specialization = PrevDecl;
Douglas Gregor6bc9f7e2009-02-25 22:18:32 +00002468 Specialization->setLocation(TemplateNameLoc);
Douglas Gregorcc636682009-02-17 23:15:12 +00002469 PrevDecl = 0;
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002470 } else if (isPartialSpecialization) {
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002471 // Create a new class template partial specialization declaration node.
2472 TemplateParameterList *TemplateParams
2473 = static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
2474 ClassTemplatePartialSpecializationDecl *PrevPartial
2475 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
2476 ClassTemplatePartialSpecializationDecl *Partial
2477 = ClassTemplatePartialSpecializationDecl::Create(Context,
2478 ClassTemplate->getDeclContext(),
Anders Carlsson91fdf6f2009-06-05 04:06:48 +00002479 TemplateNameLoc,
2480 TemplateParams,
2481 ClassTemplate,
Anders Carlssonfb250522009-06-23 01:26:57 +00002482 Converted,
Anders Carlsson91fdf6f2009-06-05 04:06:48 +00002483 PrevPartial);
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002484
2485 if (PrevPartial) {
2486 ClassTemplate->getPartialSpecializations().RemoveNode(PrevPartial);
2487 ClassTemplate->getPartialSpecializations().GetOrInsertNode(Partial);
2488 } else {
2489 ClassTemplate->getPartialSpecializations().InsertNode(Partial, InsertPos);
2490 }
2491 Specialization = Partial;
Douglas Gregor031a5882009-06-13 00:26:55 +00002492
2493 // Check that all of the template parameters of the class template
2494 // partial specialization are deducible from the template
2495 // arguments. If not, this class template partial specialization
2496 // will never be used.
2497 llvm::SmallVector<bool, 8> DeducibleParams;
2498 DeducibleParams.resize(TemplateParams->size());
2499 MarkDeducedTemplateParameters(Partial->getTemplateArgs(), DeducibleParams);
2500 unsigned NumNonDeducible = 0;
2501 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I)
2502 if (!DeducibleParams[I])
2503 ++NumNonDeducible;
2504
2505 if (NumNonDeducible) {
2506 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
2507 << (NumNonDeducible > 1)
2508 << SourceRange(TemplateNameLoc, RAngleLoc);
2509 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
2510 if (!DeducibleParams[I]) {
2511 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
2512 if (Param->getDeclName())
2513 Diag(Param->getLocation(),
2514 diag::note_partial_spec_unused_parameter)
2515 << Param->getDeclName();
2516 else
2517 Diag(Param->getLocation(),
2518 diag::note_partial_spec_unused_parameter)
2519 << std::string("<anonymous>");
2520 }
2521 }
2522 }
2523
Douglas Gregorcc636682009-02-17 23:15:12 +00002524 } else {
2525 // Create a new class template specialization declaration node for
2526 // this explicit specialization.
2527 Specialization
2528 = ClassTemplateSpecializationDecl::Create(Context,
2529 ClassTemplate->getDeclContext(),
2530 TemplateNameLoc,
Anders Carlsson91fdf6f2009-06-05 04:06:48 +00002531 ClassTemplate,
Anders Carlssonfb250522009-06-23 01:26:57 +00002532 Converted,
Douglas Gregorcc636682009-02-17 23:15:12 +00002533 PrevDecl);
2534
2535 if (PrevDecl) {
2536 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
2537 ClassTemplate->getSpecializations().GetOrInsertNode(Specialization);
2538 } else {
2539 ClassTemplate->getSpecializations().InsertNode(Specialization,
2540 InsertPos);
2541 }
2542 }
2543
2544 // Note that this is an explicit specialization.
2545 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
2546
2547 // Check that this isn't a redefinition of this specialization.
2548 if (TK == TK_Definition) {
2549 if (RecordDecl *Def = Specialization->getDefinition(Context)) {
Mike Stump390b4cc2009-05-16 07:39:55 +00002550 // FIXME: Should also handle explicit specialization after implicit
2551 // instantiation with a special diagnostic.
Douglas Gregorcc636682009-02-17 23:15:12 +00002552 SourceRange Range(TemplateNameLoc, RAngleLoc);
2553 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002554 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregorcc636682009-02-17 23:15:12 +00002555 Diag(Def->getLocation(), diag::note_previous_definition);
2556 Specialization->setInvalidDecl();
Douglas Gregor212e81c2009-03-25 00:13:59 +00002557 return true;
Douglas Gregorcc636682009-02-17 23:15:12 +00002558 }
2559 }
2560
Douglas Gregorfc705b82009-02-26 22:19:44 +00002561 // Build the fully-sugared type for this class template
2562 // specialization as the user wrote in the specialization
2563 // itself. This means that we'll pretty-print the type retrieved
2564 // from the specialization's declaration the way that the user
2565 // actually wrote the specialization, rather than formatting the
2566 // name based on the "canonical" representation used to store the
2567 // template arguments in the specialization.
Douglas Gregore6258932009-03-19 00:39:20 +00002568 QualType WrittenTy
Douglas Gregor7532dc62009-03-30 22:58:21 +00002569 = Context.getTemplateSpecializationType(Name,
Anders Carlsson6360be72009-06-13 18:20:51 +00002570 TemplateArgs.data(),
Douglas Gregor7532dc62009-03-30 22:58:21 +00002571 TemplateArgs.size(),
Douglas Gregore6258932009-03-19 00:39:20 +00002572 Context.getTypeDeclType(Specialization));
Douglas Gregor7532dc62009-03-30 22:58:21 +00002573 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregor40808ce2009-03-09 23:48:35 +00002574 TemplateArgsIn.release();
Douglas Gregorcc636682009-02-17 23:15:12 +00002575
Douglas Gregor6bc9f7e2009-02-25 22:18:32 +00002576 // C++ [temp.expl.spec]p9:
2577 // A template explicit specialization is in the scope of the
2578 // namespace in which the template was defined.
2579 //
2580 // We actually implement this paragraph where we set the semantic
2581 // context (in the creation of the ClassTemplateSpecializationDecl),
2582 // but we also maintain the lexical context where the actual
2583 // definition occurs.
Douglas Gregorcc636682009-02-17 23:15:12 +00002584 Specialization->setLexicalDeclContext(CurContext);
2585
2586 // We may be starting the definition of this specialization.
2587 if (TK == TK_Definition)
2588 Specialization->startDefinition();
2589
2590 // Add the specialization into its lexical context, so that it can
2591 // be seen when iterating through the list of declarations in that
2592 // context. However, specializations are not found by name lookup.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002593 CurContext->addDecl(Specialization);
Chris Lattnerb28317a2009-03-28 19:18:32 +00002594 return DeclPtrTy::make(Specialization);
Douglas Gregorcc636682009-02-17 23:15:12 +00002595}
Douglas Gregord57959a2009-03-27 23:10:48 +00002596
Douglas Gregore542c862009-06-23 23:11:28 +00002597Sema::DeclPtrTy
2598Sema::ActOnTemplateDeclarator(Scope *S,
2599 MultiTemplateParamsArg TemplateParameterLists,
2600 Declarator &D) {
2601 return HandleDeclarator(S, D, move(TemplateParameterLists), false);
2602}
2603
Douglas Gregor52591bf2009-06-24 00:54:41 +00002604Sema::DeclPtrTy
2605Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
2606 MultiTemplateParamsArg TemplateParameterLists,
2607 Declarator &D) {
2608 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
2609 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
2610 "Not a function declarator!");
2611 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2612
2613 if (FTI.hasPrototype) {
2614 // FIXME: Diagnose arguments without names in C.
2615 }
2616
2617 Scope *ParentScope = FnBodyScope->getParent();
2618
2619 DeclPtrTy DP = HandleDeclarator(ParentScope, D,
2620 move(TemplateParameterLists),
2621 /*IsFunctionDefinition=*/true);
Douglas Gregorf59a56e2009-07-21 23:53:31 +00002622 if (FunctionTemplateDecl *FunctionTemplate
2623 = dyn_cast_or_null<FunctionTemplateDecl>(DP.getAs<Decl>()))
Douglas Gregore53060f2009-06-25 22:08:12 +00002624 return ActOnStartOfFunctionDef(FnBodyScope,
2625 DeclPtrTy::make(FunctionTemplate->getTemplatedDecl()));
Douglas Gregorf59a56e2009-07-21 23:53:31 +00002626 if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(DP.getAs<Decl>()))
2627 return ActOnStartOfFunctionDef(FnBodyScope, DeclPtrTy::make(Function));
Douglas Gregore53060f2009-06-25 22:08:12 +00002628 return DeclPtrTy();
Douglas Gregor52591bf2009-06-24 00:54:41 +00002629}
2630
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002631// Explicit instantiation of a class template specialization
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002632Sema::DeclResult
2633Sema::ActOnExplicitInstantiation(Scope *S, SourceLocation TemplateLoc,
2634 unsigned TagSpec,
2635 SourceLocation KWLoc,
2636 const CXXScopeSpec &SS,
2637 TemplateTy TemplateD,
2638 SourceLocation TemplateNameLoc,
2639 SourceLocation LAngleLoc,
2640 ASTTemplateArgsPtr TemplateArgsIn,
2641 SourceLocation *TemplateArgLocs,
2642 SourceLocation RAngleLoc,
2643 AttributeList *Attr) {
2644 // Find the class template we're specializing
2645 TemplateName Name = TemplateD.getAsVal<TemplateName>();
2646 ClassTemplateDecl *ClassTemplate
2647 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
2648
2649 // Check that the specialization uses the same tag kind as the
2650 // original template.
2651 TagDecl::TagKind Kind;
2652 switch (TagSpec) {
2653 default: assert(0 && "Unknown tag type!");
2654 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2655 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2656 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2657 }
Douglas Gregor501c5ce2009-05-14 16:41:31 +00002658 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
2659 Kind, KWLoc,
2660 *ClassTemplate->getIdentifier())) {
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002661 Diag(KWLoc, diag::err_use_with_wrong_tag)
2662 << ClassTemplate
2663 << CodeModificationHint::CreateReplacement(KWLoc,
2664 ClassTemplate->getTemplatedDecl()->getKindName());
2665 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
2666 diag::note_previous_use);
2667 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
2668 }
2669
Douglas Gregorff668032009-05-13 18:28:20 +00002670 // C++0x [temp.explicit]p2:
2671 // [...] An explicit instantiation shall appear in an enclosing
2672 // namespace of its template. [...]
2673 //
2674 // This is C++ DR 275.
2675 if (CheckClassTemplateSpecializationScope(ClassTemplate, 0,
2676 TemplateNameLoc,
2677 SS.getRange(),
Douglas Gregor16df8502009-06-12 22:21:45 +00002678 /*PartialSpecialization=*/false,
Douglas Gregorff668032009-05-13 18:28:20 +00002679 /*ExplicitInstantiation=*/true))
2680 return true;
2681
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002682 // Translate the parser's template argument list in our AST format.
2683 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
2684 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
2685
2686 // Check that the template argument list is well-formed for this
2687 // template.
Anders Carlssonfb250522009-06-23 01:26:57 +00002688 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
2689 TemplateArgs.size());
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002690 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
Anders Carlsson9bff9a92009-06-05 02:12:32 +00002691 TemplateArgs.data(), TemplateArgs.size(),
Douglas Gregor16134c62009-07-01 00:28:38 +00002692 RAngleLoc, false, Converted))
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002693 return true;
2694
Anders Carlssonfb250522009-06-23 01:26:57 +00002695 assert((Converted.structuredSize() ==
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002696 ClassTemplate->getTemplateParameters()->size()) &&
2697 "Converted template argument list is too short!");
2698
2699 // Find the class template specialization declaration that
2700 // corresponds to these arguments.
2701 llvm::FoldingSetNodeID ID;
Anders Carlsson1c5976e2009-06-05 03:43:12 +00002702 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlssonfb250522009-06-23 01:26:57 +00002703 Converted.getFlatArguments(),
Douglas Gregor828e2262009-07-29 16:09:57 +00002704 Converted.flatSize(),
2705 Context);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002706 void *InsertPos = 0;
2707 ClassTemplateSpecializationDecl *PrevDecl
2708 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
2709
2710 ClassTemplateSpecializationDecl *Specialization = 0;
2711
Douglas Gregorff668032009-05-13 18:28:20 +00002712 bool SpecializationRequiresInstantiation = true;
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002713 if (PrevDecl) {
Douglas Gregorff668032009-05-13 18:28:20 +00002714 if (PrevDecl->getSpecializationKind() == TSK_ExplicitInstantiation) {
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002715 // This particular specialization has already been declared or
2716 // instantiated. We cannot explicitly instantiate it.
Douglas Gregorff668032009-05-13 18:28:20 +00002717 Diag(TemplateNameLoc, diag::err_explicit_instantiation_duplicate)
2718 << Context.getTypeDeclType(PrevDecl);
2719 Diag(PrevDecl->getLocation(),
2720 diag::note_previous_explicit_instantiation);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002721 return DeclPtrTy::make(PrevDecl);
2722 }
2723
Douglas Gregorff668032009-05-13 18:28:20 +00002724 if (PrevDecl->getSpecializationKind() == TSK_ExplicitSpecialization) {
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002725 // C++ DR 259, C++0x [temp.explicit]p4:
Douglas Gregorff668032009-05-13 18:28:20 +00002726 // For a given set of template parameters, if an explicit
2727 // instantiation of a template appears after a declaration of
2728 // an explicit specialization for that template, the explicit
2729 // instantiation has no effect.
2730 if (!getLangOptions().CPlusPlus0x) {
2731 Diag(TemplateNameLoc,
2732 diag::ext_explicit_instantiation_after_specialization)
2733 << Context.getTypeDeclType(PrevDecl);
2734 Diag(PrevDecl->getLocation(),
2735 diag::note_previous_template_specialization);
2736 }
2737
2738 // Create a new class template specialization declaration node
2739 // for this explicit specialization. This node is only used to
2740 // record the existence of this explicit instantiation for
2741 // accurate reproduction of the source code; we don't actually
2742 // use it for anything, since it is semantically irrelevant.
2743 Specialization
2744 = ClassTemplateSpecializationDecl::Create(Context,
2745 ClassTemplate->getDeclContext(),
2746 TemplateNameLoc,
2747 ClassTemplate,
Anders Carlssonfb250522009-06-23 01:26:57 +00002748 Converted, 0);
Douglas Gregorff668032009-05-13 18:28:20 +00002749 Specialization->setLexicalDeclContext(CurContext);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002750 CurContext->addDecl(Specialization);
Douglas Gregorff668032009-05-13 18:28:20 +00002751 return DeclPtrTy::make(Specialization);
2752 }
2753
2754 // If we have already (implicitly) instantiated this
2755 // specialization, there is less work to do.
2756 if (PrevDecl->getSpecializationKind() == TSK_ImplicitInstantiation)
2757 SpecializationRequiresInstantiation = false;
2758
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002759 // Since the only prior class template specialization with these
2760 // arguments was referenced but not declared, reuse that
2761 // declaration node as our own, updating its source location to
2762 // reflect our new declaration.
2763 Specialization = PrevDecl;
2764 Specialization->setLocation(TemplateNameLoc);
2765 PrevDecl = 0;
2766 } else {
2767 // Create a new class template specialization declaration node for
2768 // this explicit specialization.
2769 Specialization
2770 = ClassTemplateSpecializationDecl::Create(Context,
2771 ClassTemplate->getDeclContext(),
2772 TemplateNameLoc,
2773 ClassTemplate,
Anders Carlssonfb250522009-06-23 01:26:57 +00002774 Converted, 0);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002775
2776 ClassTemplate->getSpecializations().InsertNode(Specialization,
2777 InsertPos);
2778 }
2779
2780 // Build the fully-sugared type for this explicit instantiation as
2781 // the user wrote in the explicit instantiation itself. This means
2782 // that we'll pretty-print the type retrieved from the
2783 // specialization's declaration the way that the user actually wrote
2784 // the explicit instantiation, rather than formatting the name based
2785 // on the "canonical" representation used to store the template
2786 // arguments in the specialization.
2787 QualType WrittenTy
2788 = Context.getTemplateSpecializationType(Name,
Anders Carlssonf4e2a2c2009-06-05 02:45:24 +00002789 TemplateArgs.data(),
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002790 TemplateArgs.size(),
2791 Context.getTypeDeclType(Specialization));
2792 Specialization->setTypeAsWritten(WrittenTy);
2793 TemplateArgsIn.release();
2794
2795 // Add the explicit instantiation into its lexical context. However,
2796 // since explicit instantiations are never found by name lookup, we
2797 // just put it into the declaration context directly.
2798 Specialization->setLexicalDeclContext(CurContext);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002799 CurContext->addDecl(Specialization);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002800
2801 // C++ [temp.explicit]p3:
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002802 // A definition of a class template or class member template
2803 // shall be in scope at the point of the explicit instantiation of
2804 // the class template or class member template.
2805 //
2806 // This check comes when we actually try to perform the
2807 // instantiation.
Douglas Gregore2c31ff2009-05-15 17:59:04 +00002808 if (SpecializationRequiresInstantiation)
2809 InstantiateClassTemplateSpecialization(Specialization, true);
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00002810 else // Instantiate the members of this class template specialization.
Douglas Gregore2c31ff2009-05-15 17:59:04 +00002811 InstantiateClassTemplateSpecializationMembers(TemplateLoc, Specialization);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002812
2813 return DeclPtrTy::make(Specialization);
2814}
2815
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002816// Explicit instantiation of a member class of a class template.
2817Sema::DeclResult
2818Sema::ActOnExplicitInstantiation(Scope *S, SourceLocation TemplateLoc,
2819 unsigned TagSpec,
2820 SourceLocation KWLoc,
2821 const CXXScopeSpec &SS,
2822 IdentifierInfo *Name,
2823 SourceLocation NameLoc,
2824 AttributeList *Attr) {
2825
Douglas Gregor402abb52009-05-28 23:31:59 +00002826 bool Owned = false;
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002827 DeclPtrTy TagD = ActOnTag(S, TagSpec, Action::TK_Reference,
Douglas Gregor7cdbc582009-07-22 23:48:44 +00002828 KWLoc, SS, Name, NameLoc, Attr, AS_none,
2829 MultiTemplateParamsArg(*this, 0, 0), Owned);
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002830 if (!TagD)
2831 return true;
2832
2833 TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
2834 if (Tag->isEnum()) {
2835 Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
2836 << Context.getTypeDeclType(Tag);
2837 return true;
2838 }
2839
Douglas Gregord0c87372009-05-27 17:30:49 +00002840 if (Tag->isInvalidDecl())
2841 return true;
2842
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002843 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
2844 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
2845 if (!Pattern) {
2846 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
2847 << Context.getTypeDeclType(Record);
2848 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
2849 return true;
2850 }
2851
2852 // C++0x [temp.explicit]p2:
2853 // [...] An explicit instantiation shall appear in an enclosing
2854 // namespace of its template. [...]
2855 //
2856 // This is C++ DR 275.
2857 if (getLangOptions().CPlusPlus0x) {
Mike Stump390b4cc2009-05-16 07:39:55 +00002858 // FIXME: In C++98, we would like to turn these errors into warnings,
2859 // dependent on a -Wc++0x flag.
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002860 DeclContext *PatternContext
2861 = Pattern->getDeclContext()->getEnclosingNamespaceContext();
2862 if (!CurContext->Encloses(PatternContext)) {
2863 Diag(TemplateLoc, diag::err_explicit_instantiation_out_of_scope)
2864 << Record << cast<NamedDecl>(PatternContext) << SS.getRange();
2865 Diag(Pattern->getLocation(), diag::note_previous_declaration);
2866 }
2867 }
2868
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002869 if (!Record->getDefinition(Context)) {
2870 // If the class has a definition, instantiate it (and all of its
2871 // members, recursively).
2872 Pattern = cast_or_null<CXXRecordDecl>(Pattern->getDefinition(Context));
2873 if (Pattern && InstantiateClass(TemplateLoc, Record, Pattern,
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002874 getTemplateInstantiationArgs(Record),
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002875 /*ExplicitInstantiation=*/true))
2876 return true;
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00002877 } else // Instantiate all of the members of class.
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002878 InstantiateClassMembers(TemplateLoc, Record,
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002879 getTemplateInstantiationArgs(Record));
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002880
Mike Stump390b4cc2009-05-16 07:39:55 +00002881 // FIXME: We don't have any representation for explicit instantiations of
2882 // member classes. Such a representation is not needed for compilation, but it
2883 // should be available for clients that want to see all of the declarations in
2884 // the source code.
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002885 return TagD;
2886}
2887
Douglas Gregord57959a2009-03-27 23:10:48 +00002888Sema::TypeResult
2889Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
2890 const IdentifierInfo &II, SourceLocation IdLoc) {
2891 NestedNameSpecifier *NNS
2892 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
2893 if (!NNS)
2894 return true;
2895
2896 QualType T = CheckTypenameType(NNS, II, SourceRange(TypenameLoc, IdLoc));
Douglas Gregor31a19b62009-04-01 21:51:26 +00002897 if (T.isNull())
2898 return true;
Douglas Gregord57959a2009-03-27 23:10:48 +00002899 return T.getAsOpaquePtr();
2900}
2901
Douglas Gregor17343172009-04-01 00:28:59 +00002902Sema::TypeResult
2903Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
2904 SourceLocation TemplateLoc, TypeTy *Ty) {
2905 QualType T = QualType::getFromOpaquePtr(Ty);
2906 NestedNameSpecifier *NNS
2907 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
2908 const TemplateSpecializationType *TemplateId
2909 = T->getAsTemplateSpecializationType();
2910 assert(TemplateId && "Expected a template specialization type");
2911
2912 if (NNS->isDependent())
2913 return Context.getTypenameType(NNS, TemplateId).getAsOpaquePtr();
2914
2915 return Context.getQualifiedNameType(NNS, T).getAsOpaquePtr();
2916}
2917
Douglas Gregord57959a2009-03-27 23:10:48 +00002918/// \brief Build the type that describes a C++ typename specifier,
2919/// e.g., "typename T::type".
2920QualType
2921Sema::CheckTypenameType(NestedNameSpecifier *NNS, const IdentifierInfo &II,
2922 SourceRange Range) {
Douglas Gregor42af25f2009-05-11 19:58:34 +00002923 CXXRecordDecl *CurrentInstantiation = 0;
2924 if (NNS->isDependent()) {
2925 CurrentInstantiation = getCurrentInstantiationOf(NNS);
Douglas Gregord57959a2009-03-27 23:10:48 +00002926
Douglas Gregor42af25f2009-05-11 19:58:34 +00002927 // If the nested-name-specifier does not refer to the current
2928 // instantiation, then build a typename type.
2929 if (!CurrentInstantiation)
2930 return Context.getTypenameType(NNS, &II);
2931 }
Douglas Gregord57959a2009-03-27 23:10:48 +00002932
Douglas Gregor42af25f2009-05-11 19:58:34 +00002933 DeclContext *Ctx = 0;
2934
2935 if (CurrentInstantiation)
2936 Ctx = CurrentInstantiation;
2937 else {
2938 CXXScopeSpec SS;
2939 SS.setScopeRep(NNS);
2940 SS.setRange(Range);
2941 if (RequireCompleteDeclContext(SS))
2942 return QualType();
2943
2944 Ctx = computeDeclContext(SS);
2945 }
Douglas Gregord57959a2009-03-27 23:10:48 +00002946 assert(Ctx && "No declaration context?");
2947
2948 DeclarationName Name(&II);
2949 LookupResult Result = LookupQualifiedName(Ctx, Name, LookupOrdinaryName,
2950 false);
2951 unsigned DiagID = 0;
2952 Decl *Referenced = 0;
2953 switch (Result.getKind()) {
2954 case LookupResult::NotFound:
2955 if (Ctx->isTranslationUnit())
2956 DiagID = diag::err_typename_nested_not_found_global;
2957 else
2958 DiagID = diag::err_typename_nested_not_found;
2959 break;
2960
2961 case LookupResult::Found:
2962 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getAsDecl())) {
2963 // We found a type. Build a QualifiedNameType, since the
2964 // typename-specifier was just sugar. FIXME: Tell
2965 // QualifiedNameType that it has a "typename" prefix.
2966 return Context.getQualifiedNameType(NNS, Context.getTypeDeclType(Type));
2967 }
2968
2969 DiagID = diag::err_typename_nested_not_type;
2970 Referenced = Result.getAsDecl();
2971 break;
2972
2973 case LookupResult::FoundOverloaded:
2974 DiagID = diag::err_typename_nested_not_type;
2975 Referenced = *Result.begin();
2976 break;
2977
2978 case LookupResult::AmbiguousBaseSubobjectTypes:
2979 case LookupResult::AmbiguousBaseSubobjects:
2980 case LookupResult::AmbiguousReference:
2981 DiagnoseAmbiguousLookup(Result, Name, Range.getEnd(), Range);
2982 return QualType();
2983 }
2984
2985 // If we get here, it's because name lookup did not find a
2986 // type. Emit an appropriate diagnostic and return an error.
2987 if (NamedDecl *NamedCtx = dyn_cast<NamedDecl>(Ctx))
2988 Diag(Range.getEnd(), DiagID) << Range << Name << NamedCtx;
2989 else
2990 Diag(Range.getEnd(), DiagID) << Range << Name;
2991 if (Referenced)
2992 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
2993 << Name;
2994 return QualType();
2995}