blob: b15ce295ea2c94ddfa48de4defbad37df45bd7f8 [file] [log] [blame]
Douglas Gregor72c3f312008-12-05 18:15:24 +00001//===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===/
2
3//
4// The LLVM Compiler Infrastructure
5//
6// This file is distributed under the University of Illinois Open Source
7// License. See LICENSE.TXT for details.
Douglas Gregor99ebf652009-02-27 19:31:52 +00008//===----------------------------------------------------------------------===/
Douglas Gregor72c3f312008-12-05 18:15:24 +00009
10//
11// This file implements semantic analysis for C++ templates.
Douglas Gregor99ebf652009-02-27 19:31:52 +000012//===----------------------------------------------------------------------===/
Douglas Gregor72c3f312008-12-05 18:15:24 +000013
14#include "Sema.h"
Douglas Gregorddc29e12009-02-06 22:42:48 +000015#include "clang/AST/ASTContext.h"
Douglas Gregor898574e2008-12-05 23:32:09 +000016#include "clang/AST/Expr.h"
Douglas Gregorcc45cb32009-02-11 19:52:55 +000017#include "clang/AST/ExprCXX.h"
Douglas Gregoraaba5e32009-02-04 19:02:06 +000018#include "clang/AST/DeclTemplate.h"
Douglas Gregor72c3f312008-12-05 18:15:24 +000019#include "clang/Parse/DeclSpec.h"
20#include "clang/Basic/LangOptions.h"
21
22using namespace clang;
23
Douglas Gregord6fb7ef2008-12-18 19:37:40 +000024/// isTemplateName - Determines whether the identifier II is a
25/// template name in the current scope, and returns the template
26/// declaration if II names a template. An optional CXXScope can be
27/// passed to indicate the C++ scope in which the identifier will be
28/// found.
Douglas Gregorc45c2322009-03-31 00:43:58 +000029TemplateNameKind Sema::isTemplateName(const IdentifierInfo &II, Scope *S,
Douglas Gregor7532dc62009-03-30 22:58:21 +000030 TemplateTy &TemplateResult,
Douglas Gregor39a8de12009-02-25 19:37:18 +000031 const CXXScopeSpec *SS) {
Douglas Gregor47b9a1c2009-02-04 17:27:36 +000032 NamedDecl *IIDecl = LookupParsedName(S, SS, &II, LookupOrdinaryName);
Douglas Gregord6fb7ef2008-12-18 19:37:40 +000033
Douglas Gregor7532dc62009-03-30 22:58:21 +000034 TemplateNameKind TNK = TNK_Non_template;
35 TemplateDecl *Template = 0;
36
Douglas Gregord6fb7ef2008-12-18 19:37:40 +000037 if (IIDecl) {
Douglas Gregor7532dc62009-03-30 22:58:21 +000038 if ((Template = dyn_cast<TemplateDecl>(IIDecl))) {
Douglas Gregor55f6b142009-02-09 18:46:07 +000039 if (isa<FunctionTemplateDecl>(IIDecl))
Douglas Gregor7532dc62009-03-30 22:58:21 +000040 TNK = TNK_Function_template;
Douglas Gregorc45c2322009-03-31 00:43:58 +000041 else if (isa<ClassTemplateDecl>(IIDecl) ||
42 isa<TemplateTemplateParmDecl>(IIDecl))
43 TNK = TNK_Type_template;
Douglas Gregor7532dc62009-03-30 22:58:21 +000044 else
45 assert(false && "Unknown template declaration kind");
Douglas Gregorbefc20e2009-03-26 00:10:35 +000046 } else if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(IIDecl)) {
47 // C++ [temp.local]p1:
48 // Like normal (non-template) classes, class templates have an
49 // injected-class-name (Clause 9). The injected-class-name
50 // can be used with or without a template-argument-list. When
51 // it is used without a template-argument-list, it is
52 // equivalent to the injected-class-name followed by the
53 // template-parameters of the class template enclosed in
54 // <>. When it is used with a template-argument-list, it
55 // refers to the specified class template specialization,
56 // which could be the current specialization or another
57 // specialization.
58 if (Record->isInjectedClassName()) {
59 Record = cast<CXXRecordDecl>(Context.getCanonicalDecl(Record));
Douglas Gregor7532dc62009-03-30 22:58:21 +000060 if ((Template = Record->getDescribedClassTemplate()))
Douglas Gregorc45c2322009-03-31 00:43:58 +000061 TNK = TNK_Type_template;
Douglas Gregor7532dc62009-03-30 22:58:21 +000062 else if (ClassTemplateSpecializationDecl *Spec
Douglas Gregorbefc20e2009-03-26 00:10:35 +000063 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
Douglas Gregor7532dc62009-03-30 22:58:21 +000064 Template = Spec->getSpecializedTemplate();
Douglas Gregorc45c2322009-03-31 00:43:58 +000065 TNK = TNK_Type_template;
Douglas Gregorbefc20e2009-03-26 00:10:35 +000066 }
67 }
Douglas Gregor55f6b142009-02-09 18:46:07 +000068 }
Douglas Gregoraaba5e32009-02-04 19:02:06 +000069
Douglas Gregor55f6b142009-02-09 18:46:07 +000070 // FIXME: What follows is a gross hack.
Douglas Gregord6fb7ef2008-12-18 19:37:40 +000071 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(IIDecl)) {
Douglas Gregor55f6b142009-02-09 18:46:07 +000072 if (FD->getType()->isDependentType()) {
Douglas Gregor7532dc62009-03-30 22:58:21 +000073 TemplateResult = TemplateTy::make(FD);
Douglas Gregor55f6b142009-02-09 18:46:07 +000074 return TNK_Function_template;
75 }
Douglas Gregord6fb7ef2008-12-18 19:37:40 +000076 } else if (OverloadedFunctionDecl *Ovl
77 = dyn_cast<OverloadedFunctionDecl>(IIDecl)) {
78 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
79 FEnd = Ovl->function_end();
80 F != FEnd; ++F) {
Douglas Gregor55f6b142009-02-09 18:46:07 +000081 if ((*F)->getType()->isDependentType()) {
Douglas Gregor7532dc62009-03-30 22:58:21 +000082 TemplateResult = TemplateTy::make(Ovl);
Douglas Gregor55f6b142009-02-09 18:46:07 +000083 return TNK_Function_template;
84 }
Douglas Gregord6fb7ef2008-12-18 19:37:40 +000085 }
86 }
Douglas Gregor7532dc62009-03-30 22:58:21 +000087
88 if (TNK != TNK_Non_template) {
89 if (SS && SS->isSet() && !SS->isInvalid()) {
90 NestedNameSpecifier *Qualifier
91 = static_cast<NestedNameSpecifier *>(SS->getScopeRep());
92 TemplateResult
93 = TemplateTy::make(Context.getQualifiedTemplateName(Qualifier,
94 false,
95 Template));
96 } else
97 TemplateResult = TemplateTy::make(TemplateName(Template));
98 }
Douglas Gregord6fb7ef2008-12-18 19:37:40 +000099 }
Douglas Gregor7532dc62009-03-30 22:58:21 +0000100 return TNK;
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000101}
102
Douglas Gregor72c3f312008-12-05 18:15:24 +0000103/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
104/// that the template parameter 'PrevDecl' is being shadowed by a new
105/// declaration at location Loc. Returns true to indicate that this is
106/// an error, and false otherwise.
107bool Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
Douglas Gregorf57172b2008-12-08 18:40:42 +0000108 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregor72c3f312008-12-05 18:15:24 +0000109
110 // Microsoft Visual C++ permits template parameters to be shadowed.
111 if (getLangOptions().Microsoft)
112 return false;
113
114 // C++ [temp.local]p4:
115 // A template-parameter shall not be redeclared within its
116 // scope (including nested scopes).
117 Diag(Loc, diag::err_template_param_shadow)
118 << cast<NamedDecl>(PrevDecl)->getDeclName();
119 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
120 return true;
121}
122
Douglas Gregor2943aed2009-03-03 04:44:36 +0000123/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000124/// the parameter D to reference the templated declaration and return a pointer
125/// to the template declaration. Otherwise, do nothing to D and return null.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000126TemplateDecl *Sema::AdjustDeclIfTemplate(DeclPtrTy &D) {
127 if (TemplateDecl *Temp = dyn_cast<TemplateDecl>(D.getAs<Decl>())) {
128 D = DeclPtrTy::make(Temp->getTemplatedDecl());
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000129 return Temp;
130 }
131 return 0;
132}
133
Douglas Gregor72c3f312008-12-05 18:15:24 +0000134/// ActOnTypeParameter - Called when a C++ template type parameter
135/// (e.g., "typename T") has been parsed. Typename specifies whether
136/// the keyword "typename" was used to declare the type parameter
137/// (otherwise, "class" was used), and KeyLoc is the location of the
138/// "class" or "typename" keyword. ParamName is the name of the
139/// parameter (NULL indicates an unnamed template parameter) and
140/// ParamName is the location of the parameter name (if any).
141/// If the type parameter has a default argument, it will be added
142/// later via ActOnTypeParameterDefault.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000143Sema::DeclPtrTy Sema::ActOnTypeParameter(Scope *S, bool Typename,
144 SourceLocation KeyLoc,
145 IdentifierInfo *ParamName,
146 SourceLocation ParamNameLoc,
147 unsigned Depth, unsigned Position) {
Douglas Gregor72c3f312008-12-05 18:15:24 +0000148 assert(S->isTemplateParamScope() &&
149 "Template type parameter not in template parameter scope!");
150 bool Invalid = false;
151
152 if (ParamName) {
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000153 NamedDecl *PrevDecl = LookupName(S, ParamName, LookupTagName);
Douglas Gregorf57172b2008-12-08 18:40:42 +0000154 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor72c3f312008-12-05 18:15:24 +0000155 Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc,
156 PrevDecl);
157 }
158
Douglas Gregorddc29e12009-02-06 22:42:48 +0000159 SourceLocation Loc = ParamNameLoc;
160 if (!ParamName)
161 Loc = KeyLoc;
162
Douglas Gregor72c3f312008-12-05 18:15:24 +0000163 TemplateTypeParmDecl *Param
Douglas Gregorddc29e12009-02-06 22:42:48 +0000164 = TemplateTypeParmDecl::Create(Context, CurContext, Loc,
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000165 Depth, Position, ParamName, Typename);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000166 if (Invalid)
167 Param->setInvalidDecl();
168
169 if (ParamName) {
170 // Add the template parameter into the current scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000171 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor72c3f312008-12-05 18:15:24 +0000172 IdResolver.AddDecl(Param);
173 }
174
Chris Lattnerb28317a2009-03-28 19:18:32 +0000175 return DeclPtrTy::make(Param);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000176}
177
Douglas Gregord684b002009-02-10 19:49:53 +0000178/// ActOnTypeParameterDefault - Adds a default argument (the type
179/// Default) to the given template type parameter (TypeParam).
Chris Lattnerb28317a2009-03-28 19:18:32 +0000180void Sema::ActOnTypeParameterDefault(DeclPtrTy TypeParam,
Douglas Gregord684b002009-02-10 19:49:53 +0000181 SourceLocation EqualLoc,
182 SourceLocation DefaultLoc,
183 TypeTy *DefaultT) {
184 TemplateTypeParmDecl *Parm
Chris Lattnerb28317a2009-03-28 19:18:32 +0000185 = cast<TemplateTypeParmDecl>(TypeParam.getAs<Decl>());
Douglas Gregord684b002009-02-10 19:49:53 +0000186 QualType Default = QualType::getFromOpaquePtr(DefaultT);
187
188 // C++ [temp.param]p14:
189 // A template-parameter shall not be used in its own default argument.
190 // FIXME: Implement this check! Needs a recursive walk over the types.
191
192 // Check the template argument itself.
193 if (CheckTemplateArgument(Parm, Default, DefaultLoc)) {
194 Parm->setInvalidDecl();
195 return;
196 }
197
198 Parm->setDefaultArgument(Default, DefaultLoc, false);
199}
200
Douglas Gregor2943aed2009-03-03 04:44:36 +0000201/// \brief Check that the type of a non-type template parameter is
202/// well-formed.
203///
204/// \returns the (possibly-promoted) parameter type if valid;
205/// otherwise, produces a diagnostic and returns a NULL type.
206QualType
207Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
208 // C++ [temp.param]p4:
209 //
210 // A non-type template-parameter shall have one of the following
211 // (optionally cv-qualified) types:
212 //
213 // -- integral or enumeration type,
214 if (T->isIntegralType() || T->isEnumeralType() ||
215 // -- pointer to object or pointer to function,
216 (T->isPointerType() &&
217 (T->getAsPointerType()->getPointeeType()->isObjectType() ||
218 T->getAsPointerType()->getPointeeType()->isFunctionType())) ||
219 // -- reference to object or reference to function,
220 T->isReferenceType() ||
221 // -- pointer to member.
222 T->isMemberPointerType() ||
223 // If T is a dependent type, we can't do the check now, so we
224 // assume that it is well-formed.
225 T->isDependentType())
226 return T;
227 // C++ [temp.param]p8:
228 //
229 // A non-type template-parameter of type "array of T" or
230 // "function returning T" is adjusted to be of type "pointer to
231 // T" or "pointer to function returning T", respectively.
232 else if (T->isArrayType())
233 // FIXME: Keep the type prior to promotion?
234 return Context.getArrayDecayedType(T);
235 else if (T->isFunctionType())
236 // FIXME: Keep the type prior to promotion?
237 return Context.getPointerType(T);
238
239 Diag(Loc, diag::err_template_nontype_parm_bad_type)
240 << T;
241
242 return QualType();
243}
244
Douglas Gregor72c3f312008-12-05 18:15:24 +0000245/// ActOnNonTypeTemplateParameter - Called when a C++ non-type
246/// template parameter (e.g., "int Size" in "template<int Size>
247/// class Array") has been parsed. S is the current scope and D is
248/// the parsed declarator.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000249Sema::DeclPtrTy Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
250 unsigned Depth,
251 unsigned Position) {
Douglas Gregor72c3f312008-12-05 18:15:24 +0000252 QualType T = GetTypeForDeclarator(D, S);
253
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000254 assert(S->isTemplateParamScope() &&
255 "Non-type template parameter not in template parameter scope!");
Douglas Gregor72c3f312008-12-05 18:15:24 +0000256 bool Invalid = false;
257
258 IdentifierInfo *ParamName = D.getIdentifier();
259 if (ParamName) {
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000260 NamedDecl *PrevDecl = LookupName(S, ParamName, LookupTagName);
Douglas Gregorf57172b2008-12-08 18:40:42 +0000261 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor72c3f312008-12-05 18:15:24 +0000262 Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000263 PrevDecl);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000264 }
265
Douglas Gregor2943aed2009-03-03 04:44:36 +0000266 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
Douglas Gregorceef30c2009-03-09 16:46:39 +0000267 if (T.isNull()) {
Douglas Gregor2943aed2009-03-03 04:44:36 +0000268 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregorceef30c2009-03-09 16:46:39 +0000269 Invalid = true;
270 }
Douglas Gregor5d290d52009-02-10 17:43:50 +0000271
Douglas Gregor72c3f312008-12-05 18:15:24 +0000272 NonTypeTemplateParmDecl *Param
273 = NonTypeTemplateParmDecl::Create(Context, CurContext, D.getIdentifierLoc(),
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000274 Depth, Position, ParamName, T);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000275 if (Invalid)
276 Param->setInvalidDecl();
277
278 if (D.getIdentifier()) {
279 // Add the template parameter into the current scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000280 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor72c3f312008-12-05 18:15:24 +0000281 IdResolver.AddDecl(Param);
282 }
Chris Lattnerb28317a2009-03-28 19:18:32 +0000283 return DeclPtrTy::make(Param);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000284}
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000285
Douglas Gregord684b002009-02-10 19:49:53 +0000286/// \brief Adds a default argument to the given non-type template
287/// parameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000288void Sema::ActOnNonTypeTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregord684b002009-02-10 19:49:53 +0000289 SourceLocation EqualLoc,
290 ExprArg DefaultE) {
291 NonTypeTemplateParmDecl *TemplateParm
Chris Lattnerb28317a2009-03-28 19:18:32 +0000292 = cast<NonTypeTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregord684b002009-02-10 19:49:53 +0000293 Expr *Default = static_cast<Expr *>(DefaultE.get());
294
295 // C++ [temp.param]p14:
296 // A template-parameter shall not be used in its own default argument.
297 // FIXME: Implement this check! Needs a recursive walk over the types.
298
299 // Check the well-formedness of the default template argument.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000300 if (CheckTemplateArgument(TemplateParm, TemplateParm->getType(), Default)) {
Douglas Gregord684b002009-02-10 19:49:53 +0000301 TemplateParm->setInvalidDecl();
302 return;
303 }
304
Anders Carlssone9146f22009-05-01 19:49:17 +0000305 TemplateParm->setDefaultArgument(DefaultE.takeAs<Expr>());
Douglas Gregord684b002009-02-10 19:49:53 +0000306}
307
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000308
309/// ActOnTemplateTemplateParameter - Called when a C++ template template
310/// parameter (e.g. T in template <template <typename> class T> class array)
311/// has been parsed. S is the current scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000312Sema::DeclPtrTy Sema::ActOnTemplateTemplateParameter(Scope* S,
313 SourceLocation TmpLoc,
314 TemplateParamsTy *Params,
315 IdentifierInfo *Name,
316 SourceLocation NameLoc,
317 unsigned Depth,
318 unsigned Position)
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000319{
320 assert(S->isTemplateParamScope() &&
321 "Template template parameter not in template parameter scope!");
322
323 // Construct the parameter object.
324 TemplateTemplateParmDecl *Param =
325 TemplateTemplateParmDecl::Create(Context, CurContext, TmpLoc, Depth,
326 Position, Name,
327 (TemplateParameterList*)Params);
328
329 // Make sure the parameter is valid.
330 // FIXME: Decl object is not currently invalidated anywhere so this doesn't
331 // do anything yet. However, if the template parameter list or (eventual)
332 // default value is ever invalidated, that will propagate here.
333 bool Invalid = false;
334 if (Invalid) {
335 Param->setInvalidDecl();
336 }
337
338 // If the tt-param has a name, then link the identifier into the scope
339 // and lookup mechanisms.
340 if (Name) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000341 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000342 IdResolver.AddDecl(Param);
343 }
344
Chris Lattnerb28317a2009-03-28 19:18:32 +0000345 return DeclPtrTy::make(Param);
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000346}
347
Douglas Gregord684b002009-02-10 19:49:53 +0000348/// \brief Adds a default argument to the given template template
349/// parameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000350void Sema::ActOnTemplateTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregord684b002009-02-10 19:49:53 +0000351 SourceLocation EqualLoc,
352 ExprArg DefaultE) {
353 TemplateTemplateParmDecl *TemplateParm
Chris Lattnerb28317a2009-03-28 19:18:32 +0000354 = cast<TemplateTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregord684b002009-02-10 19:49:53 +0000355
356 // Since a template-template parameter's default argument is an
357 // id-expression, it must be a DeclRefExpr.
358 DeclRefExpr *Default
359 = cast<DeclRefExpr>(static_cast<Expr *>(DefaultE.get()));
360
361 // C++ [temp.param]p14:
362 // A template-parameter shall not be used in its own default argument.
363 // FIXME: Implement this check! Needs a recursive walk over the types.
364
365 // Check the well-formedness of the template argument.
366 if (!isa<TemplateDecl>(Default->getDecl())) {
367 Diag(Default->getSourceRange().getBegin(),
368 diag::err_template_arg_must_be_template)
369 << Default->getSourceRange();
370 TemplateParm->setInvalidDecl();
371 return;
372 }
373 if (CheckTemplateArgument(TemplateParm, Default)) {
374 TemplateParm->setInvalidDecl();
375 return;
376 }
377
378 DefaultE.release();
379 TemplateParm->setDefaultArgument(Default);
380}
381
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000382/// ActOnTemplateParameterList - Builds a TemplateParameterList that
383/// contains the template parameters in Params/NumParams.
384Sema::TemplateParamsTy *
385Sema::ActOnTemplateParameterList(unsigned Depth,
386 SourceLocation ExportLoc,
387 SourceLocation TemplateLoc,
388 SourceLocation LAngleLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +0000389 DeclPtrTy *Params, unsigned NumParams,
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000390 SourceLocation RAngleLoc) {
391 if (ExportLoc.isValid())
392 Diag(ExportLoc, diag::note_template_export_unsupported);
393
Douglas Gregorddc29e12009-02-06 22:42:48 +0000394 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
395 (Decl**)Params, NumParams, RAngleLoc);
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000396}
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000397
Douglas Gregor212e81c2009-03-25 00:13:59 +0000398Sema::DeclResult
Douglas Gregorddc29e12009-02-06 22:42:48 +0000399Sema::ActOnClassTemplate(Scope *S, unsigned TagSpec, TagKind TK,
400 SourceLocation KWLoc, const CXXScopeSpec &SS,
401 IdentifierInfo *Name, SourceLocation NameLoc,
402 AttributeList *Attr,
Anders Carlsson5aeccdb2009-03-26 00:52:18 +0000403 MultiTemplateParamsArg TemplateParameterLists,
404 AccessSpecifier AS) {
Douglas Gregorddc29e12009-02-06 22:42:48 +0000405 assert(TemplateParameterLists.size() > 0 && "No template parameter lists?");
406 assert(TK != TK_Reference && "Can only declare or define class templates");
Douglas Gregord684b002009-02-10 19:49:53 +0000407 bool Invalid = false;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000408
409 // Check that we can declare a template here.
410 if (CheckTemplateDeclScope(S, TemplateParameterLists))
Douglas Gregor212e81c2009-03-25 00:13:59 +0000411 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000412
413 TagDecl::TagKind Kind;
414 switch (TagSpec) {
415 default: assert(0 && "Unknown tag type!");
416 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
417 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
418 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
419 }
420
421 // There is no such thing as an unnamed class template.
422 if (!Name) {
423 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregor212e81c2009-03-25 00:13:59 +0000424 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000425 }
426
427 // Find any previous declaration with this name.
428 LookupResult Previous = LookupParsedName(S, &SS, Name, LookupOrdinaryName,
429 true);
430 assert(!Previous.isAmbiguous() && "Ambiguity in class template redecl?");
431 NamedDecl *PrevDecl = 0;
432 if (Previous.begin() != Previous.end())
433 PrevDecl = *Previous.begin();
434
435 DeclContext *SemanticContext = CurContext;
436 if (SS.isNotEmpty() && !SS.isInvalid()) {
Douglas Gregore4e5b052009-03-19 00:18:19 +0000437 SemanticContext = computeDeclContext(SS);
Douglas Gregorddc29e12009-02-06 22:42:48 +0000438
Mike Stump390b4cc2009-05-16 07:39:55 +0000439 // FIXME: need to match up several levels of template parameter lists here.
Douglas Gregorddc29e12009-02-06 22:42:48 +0000440 }
441
442 // FIXME: member templates!
443 TemplateParameterList *TemplateParams
444 = static_cast<TemplateParameterList *>(*TemplateParameterLists.release());
445
446 // If there is a previous declaration with the same name, check
447 // whether this is a valid redeclaration.
448 ClassTemplateDecl *PrevClassTemplate
449 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
450 if (PrevClassTemplate) {
451 // Ensure that the template parameter lists are compatible.
452 if (!TemplateParameterListsAreEqual(TemplateParams,
453 PrevClassTemplate->getTemplateParameters(),
454 /*Complain=*/true))
Douglas Gregor212e81c2009-03-25 00:13:59 +0000455 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000456
457 // C++ [temp.class]p4:
458 // In a redeclaration, partial specialization, explicit
459 // specialization or explicit instantiation of a class template,
460 // the class-key shall agree in kind with the original class
461 // template declaration (7.1.5.3).
462 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Douglas Gregor501c5ce2009-05-14 16:41:31 +0000463 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind, KWLoc, *Name)) {
Douglas Gregora3a83512009-04-01 23:51:29 +0000464 Diag(KWLoc, diag::err_use_with_wrong_tag)
465 << Name
466 << CodeModificationHint::CreateReplacement(KWLoc,
467 PrevRecordDecl->getKindName());
Douglas Gregorddc29e12009-02-06 22:42:48 +0000468 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregora3a83512009-04-01 23:51:29 +0000469 Kind = PrevRecordDecl->getTagKind();
Douglas Gregorddc29e12009-02-06 22:42:48 +0000470 }
471
Douglas Gregorddc29e12009-02-06 22:42:48 +0000472 // Check for redefinition of this class template.
473 if (TK == TK_Definition) {
474 if (TagDecl *Def = PrevRecordDecl->getDefinition(Context)) {
475 Diag(NameLoc, diag::err_redefinition) << Name;
476 Diag(Def->getLocation(), diag::note_previous_definition);
477 // FIXME: Would it make sense to try to "forget" the previous
478 // definition, as part of error recovery?
Douglas Gregor212e81c2009-03-25 00:13:59 +0000479 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000480 }
481 }
482 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
483 // Maybe we will complain about the shadowed template parameter.
484 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
485 // Just pretend that we didn't see the previous declaration.
486 PrevDecl = 0;
487 } else if (PrevDecl) {
488 // C++ [temp]p5:
489 // A class template shall not have the same name as any other
490 // template, class, function, object, enumeration, enumerator,
491 // namespace, or type in the same scope (3.3), except as specified
492 // in (14.5.4).
493 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
494 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor212e81c2009-03-25 00:13:59 +0000495 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000496 }
497
Douglas Gregord684b002009-02-10 19:49:53 +0000498 // Check the template parameter list of this declaration, possibly
499 // merging in the template parameter list from the previous class
500 // template declaration.
501 if (CheckTemplateParameterList(TemplateParams,
502 PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0))
503 Invalid = true;
504
Douglas Gregor7da97d02009-05-10 22:57:19 +0000505 // FIXME: If we had a scope specifier, we better have a previous template
Douglas Gregorddc29e12009-02-06 22:42:48 +0000506 // declaration!
507
Douglas Gregorbefc20e2009-03-26 00:10:35 +0000508 CXXRecordDecl *NewClass =
Douglas Gregorddc29e12009-02-06 22:42:48 +0000509 CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name,
510 PrevClassTemplate?
Douglas Gregoraafc0cc2009-05-15 19:11:46 +0000511 PrevClassTemplate->getTemplatedDecl() : 0,
512 /*DelayTypeCreation=*/true);
Douglas Gregorddc29e12009-02-06 22:42:48 +0000513
514 ClassTemplateDecl *NewTemplate
515 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
516 DeclarationName(Name), TemplateParams,
Douglas Gregor5953d8b2009-03-19 17:26:29 +0000517 NewClass, PrevClassTemplate);
Douglas Gregorbefc20e2009-03-26 00:10:35 +0000518 NewClass->setDescribedClassTemplate(NewTemplate);
519
Douglas Gregoraafc0cc2009-05-15 19:11:46 +0000520 // Build the type for the class template declaration now.
521 QualType T =
522 Context.getTypeDeclType(NewClass,
523 PrevClassTemplate?
524 PrevClassTemplate->getTemplatedDecl() : 0);
525 assert(T->isDependentType() && "Class template type is not dependent?");
526 (void)T;
527
Anders Carlsson4cbe82c2009-03-26 01:24:28 +0000528 // Set the access specifier.
529 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
530
Douglas Gregorddc29e12009-02-06 22:42:48 +0000531 // Set the lexical context of these templates
532 NewClass->setLexicalDeclContext(CurContext);
533 NewTemplate->setLexicalDeclContext(CurContext);
534
535 if (TK == TK_Definition)
536 NewClass->startDefinition();
537
538 if (Attr)
539 ProcessDeclAttributeList(NewClass, Attr);
540
541 PushOnScopeChains(NewTemplate, S);
542
Douglas Gregord684b002009-02-10 19:49:53 +0000543 if (Invalid) {
544 NewTemplate->setInvalidDecl();
545 NewClass->setInvalidDecl();
546 }
Chris Lattnerb28317a2009-03-28 19:18:32 +0000547 return DeclPtrTy::make(NewTemplate);
Douglas Gregorddc29e12009-02-06 22:42:48 +0000548}
549
Douglas Gregord684b002009-02-10 19:49:53 +0000550/// \brief Checks the validity of a template parameter list, possibly
551/// considering the template parameter list from a previous
552/// declaration.
553///
554/// If an "old" template parameter list is provided, it must be
555/// equivalent (per TemplateParameterListsAreEqual) to the "new"
556/// template parameter list.
557///
558/// \param NewParams Template parameter list for a new template
559/// declaration. This template parameter list will be updated with any
560/// default arguments that are carried through from the previous
561/// template parameter list.
562///
563/// \param OldParams If provided, template parameter list from a
564/// previous declaration of the same template. Default template
565/// arguments will be merged from the old template parameter list to
566/// the new template parameter list.
567///
568/// \returns true if an error occurred, false otherwise.
569bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
570 TemplateParameterList *OldParams) {
571 bool Invalid = false;
572
573 // C++ [temp.param]p10:
574 // The set of default template-arguments available for use with a
575 // template declaration or definition is obtained by merging the
576 // default arguments from the definition (if in scope) and all
577 // declarations in scope in the same way default function
578 // arguments are (8.3.6).
579 bool SawDefaultArgument = false;
580 SourceLocation PreviousDefaultArgLoc;
Douglas Gregorc15cb382009-02-09 23:23:08 +0000581
Mike Stump1a35fde2009-02-11 23:03:27 +0000582 // Dummy initialization to avoid warnings.
Douglas Gregor1bc69132009-02-11 20:46:19 +0000583 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregord684b002009-02-10 19:49:53 +0000584 if (OldParams)
585 OldParam = OldParams->begin();
586
587 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
588 NewParamEnd = NewParams->end();
589 NewParam != NewParamEnd; ++NewParam) {
590 // Variables used to diagnose redundant default arguments
591 bool RedundantDefaultArg = false;
592 SourceLocation OldDefaultLoc;
593 SourceLocation NewDefaultLoc;
594
595 // Variables used to diagnose missing default arguments
596 bool MissingDefaultArg = false;
597
598 // Merge default arguments for template type parameters.
599 if (TemplateTypeParmDecl *NewTypeParm
600 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
601 TemplateTypeParmDecl *OldTypeParm
602 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
603
604 if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
605 NewTypeParm->hasDefaultArgument()) {
606 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
607 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
608 SawDefaultArgument = true;
609 RedundantDefaultArg = true;
610 PreviousDefaultArgLoc = NewDefaultLoc;
611 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
612 // Merge the default argument from the old declaration to the
613 // new declaration.
614 SawDefaultArgument = true;
615 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgument(),
616 OldTypeParm->getDefaultArgumentLoc(),
617 true);
618 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
619 } else if (NewTypeParm->hasDefaultArgument()) {
620 SawDefaultArgument = true;
621 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
622 } else if (SawDefaultArgument)
623 MissingDefaultArg = true;
624 }
625 // Merge default arguments for non-type template parameters
626 else if (NonTypeTemplateParmDecl *NewNonTypeParm
627 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
628 NonTypeTemplateParmDecl *OldNonTypeParm
629 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
630 if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
631 NewNonTypeParm->hasDefaultArgument()) {
632 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
633 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
634 SawDefaultArgument = true;
635 RedundantDefaultArg = true;
636 PreviousDefaultArgLoc = NewDefaultLoc;
637 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
638 // Merge the default argument from the old declaration to the
639 // new declaration.
640 SawDefaultArgument = true;
641 // FIXME: We need to create a new kind of "default argument"
642 // expression that points to a previous template template
643 // parameter.
644 NewNonTypeParm->setDefaultArgument(
645 OldNonTypeParm->getDefaultArgument());
646 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
647 } else if (NewNonTypeParm->hasDefaultArgument()) {
648 SawDefaultArgument = true;
649 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
650 } else if (SawDefaultArgument)
651 MissingDefaultArg = true;
652 }
653 // Merge default arguments for template template parameters
654 else {
655 TemplateTemplateParmDecl *NewTemplateParm
656 = cast<TemplateTemplateParmDecl>(*NewParam);
657 TemplateTemplateParmDecl *OldTemplateParm
658 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
659 if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
660 NewTemplateParm->hasDefaultArgument()) {
661 OldDefaultLoc = OldTemplateParm->getDefaultArgumentLoc();
662 NewDefaultLoc = NewTemplateParm->getDefaultArgumentLoc();
663 SawDefaultArgument = true;
664 RedundantDefaultArg = true;
665 PreviousDefaultArgLoc = NewDefaultLoc;
666 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
667 // Merge the default argument from the old declaration to the
668 // new declaration.
669 SawDefaultArgument = true;
Mike Stump390b4cc2009-05-16 07:39:55 +0000670 // FIXME: We need to create a new kind of "default argument" expression
671 // that points to a previous template template parameter.
Douglas Gregord684b002009-02-10 19:49:53 +0000672 NewTemplateParm->setDefaultArgument(
673 OldTemplateParm->getDefaultArgument());
674 PreviousDefaultArgLoc = OldTemplateParm->getDefaultArgumentLoc();
675 } else if (NewTemplateParm->hasDefaultArgument()) {
676 SawDefaultArgument = true;
677 PreviousDefaultArgLoc = NewTemplateParm->getDefaultArgumentLoc();
678 } else if (SawDefaultArgument)
679 MissingDefaultArg = true;
680 }
681
682 if (RedundantDefaultArg) {
683 // C++ [temp.param]p12:
684 // A template-parameter shall not be given default arguments
685 // by two different declarations in the same scope.
686 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
687 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
688 Invalid = true;
689 } else if (MissingDefaultArg) {
690 // C++ [temp.param]p11:
691 // If a template-parameter has a default template-argument,
692 // all subsequent template-parameters shall have a default
693 // template-argument supplied.
694 Diag((*NewParam)->getLocation(),
695 diag::err_template_param_default_arg_missing);
696 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
697 Invalid = true;
698 }
699
700 // If we have an old template parameter list that we're merging
701 // in, move on to the next parameter.
702 if (OldParams)
703 ++OldParam;
704 }
705
706 return Invalid;
707}
Douglas Gregorc15cb382009-02-09 23:23:08 +0000708
Douglas Gregor40808ce2009-03-09 23:48:35 +0000709/// \brief Translates template arguments as provided by the parser
710/// into template arguments used by semantic analysis.
711static void
712translateTemplateArguments(ASTTemplateArgsPtr &TemplateArgsIn,
713 SourceLocation *TemplateArgLocs,
714 llvm::SmallVector<TemplateArgument, 16> &TemplateArgs) {
715 TemplateArgs.reserve(TemplateArgsIn.size());
716
717 void **Args = TemplateArgsIn.getArgs();
718 bool *ArgIsType = TemplateArgsIn.getArgIsType();
719 for (unsigned Arg = 0, Last = TemplateArgsIn.size(); Arg != Last; ++Arg) {
720 TemplateArgs.push_back(
721 ArgIsType[Arg]? TemplateArgument(TemplateArgLocs[Arg],
722 QualType::getFromOpaquePtr(Args[Arg]))
723 : TemplateArgument(reinterpret_cast<Expr *>(Args[Arg])));
724 }
725}
726
Douglas Gregorc45c2322009-03-31 00:43:58 +0000727/// \brief Build a canonical version of a template argument list.
728///
729/// This function builds a canonical version of the given template
730/// argument list, where each of the template arguments has been
731/// converted into its canonical form. This routine is typically used
732/// to canonicalize a template argument list when the template name
733/// itself is dependent. When the template name refers to an actual
734/// template declaration, Sema::CheckTemplateArgumentList should be
735/// used to check and canonicalize the template arguments.
736///
737/// \param TemplateArgs The incoming template arguments.
738///
739/// \param NumTemplateArgs The number of template arguments in \p
740/// TemplateArgs.
741///
742/// \param Canonical A vector to be filled with the canonical versions
743/// of the template arguments.
744///
745/// \param Context The ASTContext in which the template arguments live.
746static void CanonicalizeTemplateArguments(const TemplateArgument *TemplateArgs,
747 unsigned NumTemplateArgs,
748 llvm::SmallVectorImpl<TemplateArgument> &Canonical,
749 ASTContext &Context) {
750 Canonical.reserve(NumTemplateArgs);
751 for (unsigned Idx = 0; Idx < NumTemplateArgs; ++Idx) {
752 switch (TemplateArgs[Idx].getKind()) {
753 case TemplateArgument::Expression:
754 // FIXME: Build canonical expression (!)
755 Canonical.push_back(TemplateArgs[Idx]);
756 break;
757
758 case TemplateArgument::Declaration:
Douglas Gregor7da97d02009-05-10 22:57:19 +0000759 Canonical.push_back(
760 TemplateArgument(SourceLocation(),
761 Context.getCanonicalDecl(TemplateArgs[Idx].getAsDecl())));
Douglas Gregorc45c2322009-03-31 00:43:58 +0000762 break;
763
764 case TemplateArgument::Integral:
765 Canonical.push_back(TemplateArgument(SourceLocation(),
766 *TemplateArgs[Idx].getAsIntegral(),
767 TemplateArgs[Idx].getIntegralType()));
768
769 case TemplateArgument::Type: {
770 QualType CanonType
771 = Context.getCanonicalType(TemplateArgs[Idx].getAsType());
772 Canonical.push_back(TemplateArgument(SourceLocation(), CanonType));
773 }
774 }
775 }
776}
777
Douglas Gregor7532dc62009-03-30 22:58:21 +0000778QualType Sema::CheckTemplateIdType(TemplateName Name,
779 SourceLocation TemplateLoc,
780 SourceLocation LAngleLoc,
781 const TemplateArgument *TemplateArgs,
782 unsigned NumTemplateArgs,
783 SourceLocation RAngleLoc) {
784 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregorc45c2322009-03-31 00:43:58 +0000785 if (!Template) {
786 // The template name does not resolve to a template, so we just
787 // build a dependent template-id type.
788
789 // Canonicalize the template arguments to build the canonical
790 // template-id type.
791 llvm::SmallVector<TemplateArgument, 16> CanonicalTemplateArgs;
792 CanonicalizeTemplateArguments(TemplateArgs, NumTemplateArgs,
793 CanonicalTemplateArgs, Context);
794
Douglas Gregor45fbaf02009-05-07 06:49:52 +0000795 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
Douglas Gregorc45c2322009-03-31 00:43:58 +0000796 QualType CanonType
Douglas Gregor45fbaf02009-05-07 06:49:52 +0000797 = Context.getTemplateSpecializationType(CanonName,
798 &CanonicalTemplateArgs[0],
Douglas Gregorc45c2322009-03-31 00:43:58 +0000799 CanonicalTemplateArgs.size());
800
801 // Build the dependent template-id type.
802 return Context.getTemplateSpecializationType(Name, TemplateArgs,
803 NumTemplateArgs, CanonType);
804 }
Douglas Gregor7532dc62009-03-30 22:58:21 +0000805
Douglas Gregor40808ce2009-03-09 23:48:35 +0000806 // Check that the template argument list is well-formed for this
807 // template.
808 llvm::SmallVector<TemplateArgument, 16> ConvertedTemplateArgs;
Douglas Gregor7532dc62009-03-30 22:58:21 +0000809 if (CheckTemplateArgumentList(Template, TemplateLoc, LAngleLoc,
Douglas Gregor40808ce2009-03-09 23:48:35 +0000810 TemplateArgs, NumTemplateArgs, RAngleLoc,
811 ConvertedTemplateArgs))
812 return QualType();
813
814 assert((ConvertedTemplateArgs.size() ==
Douglas Gregor7532dc62009-03-30 22:58:21 +0000815 Template->getTemplateParameters()->size()) &&
Douglas Gregor40808ce2009-03-09 23:48:35 +0000816 "Converted template argument list is too short!");
817
818 QualType CanonType;
819
Douglas Gregor7532dc62009-03-30 22:58:21 +0000820 if (TemplateSpecializationType::anyDependentTemplateArguments(
Douglas Gregor40808ce2009-03-09 23:48:35 +0000821 TemplateArgs,
822 NumTemplateArgs)) {
823 // This class template specialization is a dependent
824 // type. Therefore, its canonical type is another class template
825 // specialization type that contains all of the converted
826 // arguments in canonical form. This ensures that, e.g., A<T> and
827 // A<T, T> have identical types when A is declared as:
828 //
829 // template<typename T, typename U = T> struct A;
Douglas Gregor25a3ef72009-05-07 06:41:52 +0000830 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
831 CanonType = Context.getTemplateSpecializationType(CanonName,
Douglas Gregor40808ce2009-03-09 23:48:35 +0000832 &ConvertedTemplateArgs[0],
833 ConvertedTemplateArgs.size());
Douglas Gregor7532dc62009-03-30 22:58:21 +0000834 } else if (ClassTemplateDecl *ClassTemplate
835 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregor40808ce2009-03-09 23:48:35 +0000836 // Find the class template specialization declaration that
837 // corresponds to these arguments.
838 llvm::FoldingSetNodeID ID;
839 ClassTemplateSpecializationDecl::Profile(ID, &ConvertedTemplateArgs[0],
840 ConvertedTemplateArgs.size());
841 void *InsertPos = 0;
842 ClassTemplateSpecializationDecl *Decl
843 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
844 if (!Decl) {
845 // This is the first time we have referenced this class template
846 // specialization. Create the canonical declaration and add it to
847 // the set of specializations.
848 Decl = ClassTemplateSpecializationDecl::Create(Context,
849 ClassTemplate->getDeclContext(),
850 TemplateLoc,
851 ClassTemplate,
852 &ConvertedTemplateArgs[0],
853 ConvertedTemplateArgs.size(),
854 0);
855 ClassTemplate->getSpecializations().InsertNode(Decl, InsertPos);
856 Decl->setLexicalDeclContext(CurContext);
857 }
858
859 CanonType = Context.getTypeDeclType(Decl);
860 }
861
862 // Build the fully-sugared type for this class template
863 // specialization, which refers back to the class template
864 // specialization we created or found.
Douglas Gregor7532dc62009-03-30 22:58:21 +0000865 return Context.getTemplateSpecializationType(Name, TemplateArgs,
866 NumTemplateArgs, CanonType);
Douglas Gregor40808ce2009-03-09 23:48:35 +0000867}
868
Douglas Gregorcc636682009-02-17 23:15:12 +0000869Action::TypeResult
Douglas Gregor7532dc62009-03-30 22:58:21 +0000870Sema::ActOnTemplateIdType(TemplateTy TemplateD, SourceLocation TemplateLoc,
871 SourceLocation LAngleLoc,
872 ASTTemplateArgsPtr TemplateArgsIn,
873 SourceLocation *TemplateArgLocs,
874 SourceLocation RAngleLoc) {
875 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Douglas Gregor55f6b142009-02-09 18:46:07 +0000876
Douglas Gregor40808ce2009-03-09 23:48:35 +0000877 // Translate the parser's template argument list in our AST format.
878 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
879 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
Douglas Gregorc15cb382009-02-09 23:23:08 +0000880
Douglas Gregor7532dc62009-03-30 22:58:21 +0000881 QualType Result = CheckTemplateIdType(Template, TemplateLoc, LAngleLoc,
Jay Foadbeaaccd2009-05-21 09:52:38 +0000882 TemplateArgs.data(),
883 TemplateArgs.size(),
Douglas Gregor7532dc62009-03-30 22:58:21 +0000884 RAngleLoc);
Douglas Gregor40808ce2009-03-09 23:48:35 +0000885 TemplateArgsIn.release();
Douglas Gregor31a19b62009-04-01 21:51:26 +0000886
887 if (Result.isNull())
888 return true;
889
Douglas Gregor5908e9f2009-02-09 19:34:22 +0000890 return Result.getAsOpaquePtr();
Douglas Gregor55f6b142009-02-09 18:46:07 +0000891}
892
Douglas Gregorc45c2322009-03-31 00:43:58 +0000893/// \brief Form a dependent template name.
894///
895/// This action forms a dependent template name given the template
896/// name and its (presumably dependent) scope specifier. For
897/// example, given "MetaFun::template apply", the scope specifier \p
898/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
899/// of the "template" keyword, and "apply" is the \p Name.
900Sema::TemplateTy
901Sema::ActOnDependentTemplateName(SourceLocation TemplateKWLoc,
902 const IdentifierInfo &Name,
903 SourceLocation NameLoc,
904 const CXXScopeSpec &SS) {
905 if (!SS.isSet() || SS.isInvalid())
906 return TemplateTy();
907
908 NestedNameSpecifier *Qualifier
909 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
910
911 // FIXME: member of the current instantiation
912
913 if (!Qualifier->isDependent()) {
914 // C++0x [temp.names]p5:
915 // If a name prefixed by the keyword template is not the name of
916 // a template, the program is ill-formed. [Note: the keyword
917 // template may not be applied to non-template members of class
918 // templates. -end note ] [ Note: as is the case with the
919 // typename prefix, the template prefix is allowed in cases
920 // where it is not strictly necessary; i.e., when the
921 // nested-name-specifier or the expression on the left of the ->
922 // or . is not dependent on a template-parameter, or the use
923 // does not appear in the scope of a template. -end note]
924 //
925 // Note: C++03 was more strict here, because it banned the use of
926 // the "template" keyword prior to a template-name that was not a
927 // dependent name. C++ DR468 relaxed this requirement (the
928 // "template" keyword is now permitted). We follow the C++0x
929 // rules, even in C++03 mode, retroactively applying the DR.
930 TemplateTy Template;
931 TemplateNameKind TNK = isTemplateName(Name, 0, Template, &SS);
932 if (TNK == TNK_Non_template) {
933 Diag(NameLoc, diag::err_template_kw_refers_to_non_template)
934 << &Name;
935 return TemplateTy();
936 }
937
938 return Template;
939 }
940
941 return TemplateTy::make(Context.getDependentTemplateName(Qualifier, &Name));
942}
943
Douglas Gregorc15cb382009-02-09 23:23:08 +0000944/// \brief Check that the given template argument list is well-formed
945/// for specializing the given template.
946bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
947 SourceLocation TemplateLoc,
948 SourceLocation LAngleLoc,
Douglas Gregor40808ce2009-03-09 23:48:35 +0000949 const TemplateArgument *TemplateArgs,
950 unsigned NumTemplateArgs,
Douglas Gregor3e00bad2009-02-17 01:05:43 +0000951 SourceLocation RAngleLoc,
952 llvm::SmallVectorImpl<TemplateArgument> &Converted) {
Douglas Gregorc15cb382009-02-09 23:23:08 +0000953 TemplateParameterList *Params = Template->getTemplateParameters();
954 unsigned NumParams = Params->size();
Douglas Gregor40808ce2009-03-09 23:48:35 +0000955 unsigned NumArgs = NumTemplateArgs;
Douglas Gregorc15cb382009-02-09 23:23:08 +0000956 bool Invalid = false;
957
958 if (NumArgs > NumParams ||
Douglas Gregor62cb18d2009-02-11 18:16:40 +0000959 NumArgs < Params->getMinRequiredArguments()) {
Douglas Gregorc15cb382009-02-09 23:23:08 +0000960 // FIXME: point at either the first arg beyond what we can handle,
961 // or the '>', depending on whether we have too many or too few
962 // arguments.
963 SourceRange Range;
964 if (NumArgs > NumParams)
Douglas Gregor40808ce2009-03-09 23:48:35 +0000965 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
Douglas Gregorc15cb382009-02-09 23:23:08 +0000966 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
967 << (NumArgs > NumParams)
968 << (isa<ClassTemplateDecl>(Template)? 0 :
969 isa<FunctionTemplateDecl>(Template)? 1 :
970 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
971 << Template << Range;
Douglas Gregor62cb18d2009-02-11 18:16:40 +0000972 Diag(Template->getLocation(), diag::note_template_decl_here)
973 << Params->getSourceRange();
Douglas Gregorc15cb382009-02-09 23:23:08 +0000974 Invalid = true;
975 }
976
977 // C++ [temp.arg]p1:
978 // [...] The type and form of each template-argument specified in
979 // a template-id shall match the type and form specified for the
980 // corresponding parameter declared by the template in its
981 // template-parameter-list.
982 unsigned ArgIdx = 0;
983 for (TemplateParameterList::iterator Param = Params->begin(),
984 ParamEnd = Params->end();
985 Param != ParamEnd; ++Param, ++ArgIdx) {
986 // Decode the template argument
Douglas Gregor40808ce2009-03-09 23:48:35 +0000987 TemplateArgument Arg;
Douglas Gregorc15cb382009-02-09 23:23:08 +0000988 if (ArgIdx >= NumArgs) {
Douglas Gregor3e00bad2009-02-17 01:05:43 +0000989 // Retrieve the default template argument from the template
990 // parameter.
991 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
992 if (!TTP->hasDefaultArgument())
993 break;
994
Douglas Gregor40808ce2009-03-09 23:48:35 +0000995 QualType ArgType = TTP->getDefaultArgument();
Douglas Gregor99ebf652009-02-27 19:31:52 +0000996
997 // If the argument type is dependent, instantiate it now based
998 // on the previously-computed template arguments.
Douglas Gregordf667e72009-03-10 20:44:00 +0000999 if (ArgType->isDependentType()) {
1000 InstantiatingTemplate Inst(*this, TemplateLoc,
1001 Template, &Converted[0],
1002 Converted.size(),
1003 SourceRange(TemplateLoc, RAngleLoc));
Douglas Gregor7e063902009-05-11 23:53:27 +00001004
1005 TemplateArgumentList TemplateArgs(Context, &Converted[0],
1006 Converted.size(),
1007 /*CopyArgs=*/false);
1008 ArgType = InstantiateType(ArgType, TemplateArgs,
Douglas Gregor99ebf652009-02-27 19:31:52 +00001009 TTP->getDefaultArgumentLoc(),
1010 TTP->getDeclName());
Douglas Gregordf667e72009-03-10 20:44:00 +00001011 }
Douglas Gregor99ebf652009-02-27 19:31:52 +00001012
1013 if (ArgType.isNull())
Douglas Gregorcd281c32009-02-28 00:25:32 +00001014 return true;
Douglas Gregor99ebf652009-02-27 19:31:52 +00001015
Douglas Gregor40808ce2009-03-09 23:48:35 +00001016 Arg = TemplateArgument(TTP->getLocation(), ArgType);
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001017 } else if (NonTypeTemplateParmDecl *NTTP
1018 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
1019 if (!NTTP->hasDefaultArgument())
1020 break;
1021
Douglas Gregor2943aed2009-03-03 04:44:36 +00001022 // FIXME: Instantiate default argument
Douglas Gregor40808ce2009-03-09 23:48:35 +00001023 Arg = TemplateArgument(NTTP->getDefaultArgument());
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001024 } else {
1025 TemplateTemplateParmDecl *TempParm
1026 = cast<TemplateTemplateParmDecl>(*Param);
1027
1028 if (!TempParm->hasDefaultArgument())
1029 break;
1030
Douglas Gregor2943aed2009-03-03 04:44:36 +00001031 // FIXME: Instantiate default argument
Douglas Gregor40808ce2009-03-09 23:48:35 +00001032 Arg = TemplateArgument(TempParm->getDefaultArgument());
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001033 }
1034 } else {
1035 // Retrieve the template argument produced by the user.
Douglas Gregor40808ce2009-03-09 23:48:35 +00001036 Arg = TemplateArgs[ArgIdx];
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001037 }
1038
Douglas Gregorc15cb382009-02-09 23:23:08 +00001039
1040 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
1041 // Check template type parameters.
Douglas Gregor40808ce2009-03-09 23:48:35 +00001042 if (Arg.getKind() == TemplateArgument::Type) {
1043 if (CheckTemplateArgument(TTP, Arg.getAsType(), Arg.getLocation()))
Douglas Gregorc15cb382009-02-09 23:23:08 +00001044 Invalid = true;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001045
1046 // Add the converted template type argument.
1047 Converted.push_back(
Douglas Gregor40808ce2009-03-09 23:48:35 +00001048 TemplateArgument(Arg.getLocation(),
1049 Context.getCanonicalType(Arg.getAsType())));
Douglas Gregorc15cb382009-02-09 23:23:08 +00001050 continue;
1051 }
1052
1053 // C++ [temp.arg.type]p1:
1054 // A template-argument for a template-parameter which is a
1055 // type shall be a type-id.
1056
1057 // We have a template type parameter but the template argument
Douglas Gregor40808ce2009-03-09 23:48:35 +00001058 // is not a type.
1059 Diag(Arg.getLocation(), diag::err_template_arg_must_be_type);
Douglas Gregor8b642592009-02-10 00:53:15 +00001060 Diag((*Param)->getLocation(), diag::note_template_param_here);
Douglas Gregorc15cb382009-02-09 23:23:08 +00001061 Invalid = true;
1062 } else if (NonTypeTemplateParmDecl *NTTP
1063 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
1064 // Check non-type template parameters.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001065
1066 // Instantiate the type of the non-type template parameter with
1067 // the template arguments we've seen thus far.
1068 QualType NTTPType = NTTP->getType();
1069 if (NTTPType->isDependentType()) {
1070 // Instantiate the type of the non-type template parameter.
Douglas Gregordf667e72009-03-10 20:44:00 +00001071 InstantiatingTemplate Inst(*this, TemplateLoc,
1072 Template, &Converted[0],
1073 Converted.size(),
1074 SourceRange(TemplateLoc, RAngleLoc));
1075
Douglas Gregor7e063902009-05-11 23:53:27 +00001076 TemplateArgumentList TemplateArgs(Context, &Converted[0],
1077 Converted.size(),
1078 /*CopyArgs=*/false);
1079 NTTPType = InstantiateType(NTTPType, TemplateArgs,
Douglas Gregor2943aed2009-03-03 04:44:36 +00001080 NTTP->getLocation(),
1081 NTTP->getDeclName());
1082 // If that worked, check the non-type template parameter type
1083 // for validity.
1084 if (!NTTPType.isNull())
1085 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
1086 NTTP->getLocation());
1087
1088 if (NTTPType.isNull()) {
1089 Invalid = true;
1090 break;
1091 }
1092 }
1093
Douglas Gregor40808ce2009-03-09 23:48:35 +00001094 switch (Arg.getKind()) {
1095 case TemplateArgument::Expression: {
1096 Expr *E = Arg.getAsExpr();
1097 if (CheckTemplateArgument(NTTP, NTTPType, E, &Converted))
Douglas Gregorc15cb382009-02-09 23:23:08 +00001098 Invalid = true;
Douglas Gregor40808ce2009-03-09 23:48:35 +00001099 break;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001100 }
1101
Douglas Gregor40808ce2009-03-09 23:48:35 +00001102 case TemplateArgument::Declaration:
1103 case TemplateArgument::Integral:
1104 // We've already checked this template argument, so just copy
1105 // it to the list of converted arguments.
1106 Converted.push_back(Arg);
1107 break;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001108
Douglas Gregor40808ce2009-03-09 23:48:35 +00001109 case TemplateArgument::Type:
1110 // We have a non-type template parameter but the template
1111 // argument is a type.
1112
1113 // C++ [temp.arg]p2:
1114 // In a template-argument, an ambiguity between a type-id and
1115 // an expression is resolved to a type-id, regardless of the
1116 // form of the corresponding template-parameter.
1117 //
1118 // We warn specifically about this case, since it can be rather
1119 // confusing for users.
1120 if (Arg.getAsType()->isFunctionType())
1121 Diag(Arg.getLocation(), diag::err_template_arg_nontype_ambig)
1122 << Arg.getAsType();
1123 else
1124 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr);
1125 Diag((*Param)->getLocation(), diag::note_template_param_here);
1126 Invalid = true;
1127 }
Douglas Gregorc15cb382009-02-09 23:23:08 +00001128 } else {
1129 // Check template template parameters.
1130 TemplateTemplateParmDecl *TempParm
1131 = cast<TemplateTemplateParmDecl>(*Param);
1132
Douglas Gregor40808ce2009-03-09 23:48:35 +00001133 switch (Arg.getKind()) {
1134 case TemplateArgument::Expression: {
1135 Expr *ArgExpr = Arg.getAsExpr();
1136 if (ArgExpr && isa<DeclRefExpr>(ArgExpr) &&
1137 isa<TemplateDecl>(cast<DeclRefExpr>(ArgExpr)->getDecl())) {
1138 if (CheckTemplateArgument(TempParm, cast<DeclRefExpr>(ArgExpr)))
1139 Invalid = true;
1140
1141 // Add the converted template argument.
Douglas Gregor7da97d02009-05-10 22:57:19 +00001142 Decl *D
1143 = Context.getCanonicalDecl(cast<DeclRefExpr>(ArgExpr)->getDecl());
1144 Converted.push_back(TemplateArgument(Arg.getLocation(), D));
Douglas Gregor40808ce2009-03-09 23:48:35 +00001145 continue;
1146 }
1147 }
1148 // fall through
1149
1150 case TemplateArgument::Type: {
1151 // We have a template template parameter but the template
1152 // argument does not refer to a template.
1153 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
1154 Invalid = true;
1155 break;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001156 }
1157
Douglas Gregor40808ce2009-03-09 23:48:35 +00001158 case TemplateArgument::Declaration:
1159 // We've already checked this template argument, so just copy
1160 // it to the list of converted arguments.
1161 Converted.push_back(Arg);
1162 break;
1163
1164 case TemplateArgument::Integral:
1165 assert(false && "Integral argument with template template parameter");
1166 break;
1167 }
Douglas Gregorc15cb382009-02-09 23:23:08 +00001168 }
1169 }
1170
1171 return Invalid;
1172}
1173
1174/// \brief Check a template argument against its corresponding
1175/// template type parameter.
1176///
1177/// This routine implements the semantics of C++ [temp.arg.type]. It
1178/// returns true if an error occurred, and false otherwise.
1179bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
1180 QualType Arg, SourceLocation ArgLoc) {
1181 // C++ [temp.arg.type]p2:
1182 // A local type, a type with no linkage, an unnamed type or a type
1183 // compounded from any of these types shall not be used as a
1184 // template-argument for a template type-parameter.
1185 //
1186 // FIXME: Perform the recursive and no-linkage type checks.
1187 const TagType *Tag = 0;
1188 if (const EnumType *EnumT = Arg->getAsEnumType())
1189 Tag = EnumT;
1190 else if (const RecordType *RecordT = Arg->getAsRecordType())
1191 Tag = RecordT;
1192 if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod())
1193 return Diag(ArgLoc, diag::err_template_arg_local_type)
1194 << QualType(Tag, 0);
Douglas Gregor98137532009-03-10 18:33:27 +00001195 else if (Tag && !Tag->getDecl()->getDeclName() &&
1196 !Tag->getDecl()->getTypedefForAnonDecl()) {
Douglas Gregorc15cb382009-02-09 23:23:08 +00001197 Diag(ArgLoc, diag::err_template_arg_unnamed_type);
1198 Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here);
1199 return true;
1200 }
1201
1202 return false;
1203}
1204
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001205/// \brief Checks whether the given template argument is the address
1206/// of an object or function according to C++ [temp.arg.nontype]p1.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001207bool Sema::CheckTemplateArgumentAddressOfObjectOrFunction(Expr *Arg,
1208 NamedDecl *&Entity) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001209 bool Invalid = false;
1210
1211 // See through any implicit casts we added to fix the type.
1212 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
1213 Arg = Cast->getSubExpr();
1214
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001215 // C++0x allows nullptr, and there's no further checking to be done for that.
1216 if (Arg->getType()->isNullPtrType())
1217 return false;
1218
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001219 // C++ [temp.arg.nontype]p1:
1220 //
1221 // A template-argument for a non-type, non-template
1222 // template-parameter shall be one of: [...]
1223 //
1224 // -- the address of an object or function with external
1225 // linkage, including function templates and function
1226 // template-ids but excluding non-static class members,
1227 // expressed as & id-expression where the & is optional if
1228 // the name refers to a function or array, or if the
1229 // corresponding template-parameter is a reference; or
1230 DeclRefExpr *DRE = 0;
1231
1232 // Ignore (and complain about) any excess parentheses.
1233 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
1234 if (!Invalid) {
1235 Diag(Arg->getSourceRange().getBegin(),
1236 diag::err_template_arg_extra_parens)
1237 << Arg->getSourceRange();
1238 Invalid = true;
1239 }
1240
1241 Arg = Parens->getSubExpr();
1242 }
1243
1244 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
1245 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
1246 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
1247 } else
1248 DRE = dyn_cast<DeclRefExpr>(Arg);
1249
1250 if (!DRE || !isa<ValueDecl>(DRE->getDecl()))
1251 return Diag(Arg->getSourceRange().getBegin(),
1252 diag::err_template_arg_not_object_or_func_form)
1253 << Arg->getSourceRange();
1254
1255 // Cannot refer to non-static data members
1256 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl()))
1257 return Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
1258 << Field << Arg->getSourceRange();
1259
1260 // Cannot refer to non-static member functions
1261 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
1262 if (!Method->isStatic())
1263 return Diag(Arg->getSourceRange().getBegin(),
1264 diag::err_template_arg_method)
1265 << Method << Arg->getSourceRange();
1266
1267 // Functions must have external linkage.
1268 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
1269 if (Func->getStorageClass() == FunctionDecl::Static) {
1270 Diag(Arg->getSourceRange().getBegin(),
1271 diag::err_template_arg_function_not_extern)
1272 << Func << Arg->getSourceRange();
1273 Diag(Func->getLocation(), diag::note_template_arg_internal_object)
1274 << true;
1275 return true;
1276 }
1277
1278 // Okay: we've named a function with external linkage.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001279 Entity = Func;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001280 return Invalid;
1281 }
1282
1283 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
1284 if (!Var->hasGlobalStorage()) {
1285 Diag(Arg->getSourceRange().getBegin(),
1286 diag::err_template_arg_object_not_extern)
1287 << Var << Arg->getSourceRange();
1288 Diag(Var->getLocation(), diag::note_template_arg_internal_object)
1289 << true;
1290 return true;
1291 }
1292
1293 // Okay: we've named an object with external linkage
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001294 Entity = Var;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001295 return Invalid;
1296 }
1297
1298 // We found something else, but we don't know specifically what it is.
1299 Diag(Arg->getSourceRange().getBegin(),
1300 diag::err_template_arg_not_object_or_func)
1301 << Arg->getSourceRange();
1302 Diag(DRE->getDecl()->getLocation(),
1303 diag::note_template_arg_refers_here);
1304 return true;
1305}
1306
1307/// \brief Checks whether the given template argument is a pointer to
1308/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001309bool
1310Sema::CheckTemplateArgumentPointerToMember(Expr *Arg, NamedDecl *&Member) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001311 bool Invalid = false;
1312
1313 // See through any implicit casts we added to fix the type.
1314 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
1315 Arg = Cast->getSubExpr();
1316
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001317 // C++0x allows nullptr, and there's no further checking to be done for that.
1318 if (Arg->getType()->isNullPtrType())
1319 return false;
1320
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001321 // C++ [temp.arg.nontype]p1:
1322 //
1323 // A template-argument for a non-type, non-template
1324 // template-parameter shall be one of: [...]
1325 //
1326 // -- a pointer to member expressed as described in 5.3.1.
1327 QualifiedDeclRefExpr *DRE = 0;
1328
1329 // Ignore (and complain about) any excess parentheses.
1330 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
1331 if (!Invalid) {
1332 Diag(Arg->getSourceRange().getBegin(),
1333 diag::err_template_arg_extra_parens)
1334 << Arg->getSourceRange();
1335 Invalid = true;
1336 }
1337
1338 Arg = Parens->getSubExpr();
1339 }
1340
1341 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg))
1342 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
1343 DRE = dyn_cast<QualifiedDeclRefExpr>(UnOp->getSubExpr());
1344
1345 if (!DRE)
1346 return Diag(Arg->getSourceRange().getBegin(),
1347 diag::err_template_arg_not_pointer_to_member_form)
1348 << Arg->getSourceRange();
1349
1350 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
1351 assert((isa<FieldDecl>(DRE->getDecl()) ||
1352 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
1353 "Only non-static member pointers can make it here");
1354
1355 // Okay: this is the address of a non-static member, and therefore
1356 // a member pointer constant.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001357 Member = DRE->getDecl();
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001358 return Invalid;
1359 }
1360
1361 // We found something else, but we don't know specifically what it is.
1362 Diag(Arg->getSourceRange().getBegin(),
1363 diag::err_template_arg_not_pointer_to_member_form)
1364 << Arg->getSourceRange();
1365 Diag(DRE->getDecl()->getLocation(),
1366 diag::note_template_arg_refers_here);
1367 return true;
1368}
1369
Douglas Gregorc15cb382009-02-09 23:23:08 +00001370/// \brief Check a template argument against its corresponding
1371/// non-type template parameter.
1372///
Douglas Gregor2943aed2009-03-03 04:44:36 +00001373/// This routine implements the semantics of C++ [temp.arg.nontype].
1374/// It returns true if an error occurred, and false otherwise. \p
1375/// InstantiatedParamType is the type of the non-type template
1376/// parameter after it has been instantiated.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001377///
1378/// If Converted is non-NULL and no errors occur, the value
1379/// of this argument will be added to the end of the Converted vector.
Douglas Gregorc15cb382009-02-09 23:23:08 +00001380bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Douglas Gregor2943aed2009-03-03 04:44:36 +00001381 QualType InstantiatedParamType, Expr *&Arg,
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001382 llvm::SmallVectorImpl<TemplateArgument> *Converted) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00001383 SourceLocation StartLoc = Arg->getSourceRange().getBegin();
1384
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001385 // If either the parameter has a dependent type or the argument is
1386 // type-dependent, there's nothing we can check now.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001387 // FIXME: Add template argument to Converted!
Douglas Gregor40808ce2009-03-09 23:48:35 +00001388 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
1389 // FIXME: Produce a cloned, canonical expression?
1390 Converted->push_back(TemplateArgument(Arg));
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001391 return false;
Douglas Gregor40808ce2009-03-09 23:48:35 +00001392 }
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001393
1394 // C++ [temp.arg.nontype]p5:
1395 // The following conversions are performed on each expression used
1396 // as a non-type template-argument. If a non-type
1397 // template-argument cannot be converted to the type of the
1398 // corresponding template-parameter then the program is
1399 // ill-formed.
1400 //
1401 // -- for a non-type template-parameter of integral or
1402 // enumeration type, integral promotions (4.5) and integral
1403 // conversions (4.7) are applied.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001404 QualType ParamType = InstantiatedParamType;
Douglas Gregora35284b2009-02-11 00:19:33 +00001405 QualType ArgType = Arg->getType();
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001406 if (ParamType->isIntegralType() || ParamType->isEnumeralType()) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001407 // C++ [temp.arg.nontype]p1:
1408 // A template-argument for a non-type, non-template
1409 // template-parameter shall be one of:
1410 //
1411 // -- an integral constant-expression of integral or enumeration
1412 // type; or
1413 // -- the name of a non-type template-parameter; or
1414 SourceLocation NonConstantLoc;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001415 llvm::APSInt Value;
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001416 if (!ArgType->isIntegralType() && !ArgType->isEnumeralType()) {
1417 Diag(Arg->getSourceRange().getBegin(),
1418 diag::err_template_arg_not_integral_or_enumeral)
1419 << ArgType << Arg->getSourceRange();
1420 Diag(Param->getLocation(), diag::note_template_param_here);
1421 return true;
1422 } else if (!Arg->isValueDependent() &&
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001423 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001424 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
1425 << ArgType << Arg->getSourceRange();
1426 return true;
1427 }
1428
1429 // FIXME: We need some way to more easily get the unqualified form
1430 // of the types without going all the way to the
1431 // canonical type.
1432 if (Context.getCanonicalType(ParamType).getCVRQualifiers())
1433 ParamType = Context.getCanonicalType(ParamType).getUnqualifiedType();
1434 if (Context.getCanonicalType(ArgType).getCVRQualifiers())
1435 ArgType = Context.getCanonicalType(ArgType).getUnqualifiedType();
1436
1437 // Try to convert the argument to the parameter's type.
1438 if (ParamType == ArgType) {
1439 // Okay: no conversion necessary
1440 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
1441 !ParamType->isEnumeralType()) {
1442 // This is an integral promotion or conversion.
1443 ImpCastExprToType(Arg, ParamType);
1444 } else {
1445 // We can't perform this conversion.
1446 Diag(Arg->getSourceRange().getBegin(),
1447 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00001448 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001449 Diag(Param->getLocation(), diag::note_template_param_here);
1450 return true;
1451 }
1452
Douglas Gregorf80a9d52009-03-14 00:20:21 +00001453 QualType IntegerType = Context.getCanonicalType(ParamType);
1454 if (const EnumType *Enum = IntegerType->getAsEnumType())
1455 IntegerType = Enum->getDecl()->getIntegerType();
1456
1457 if (!Arg->isValueDependent()) {
1458 // Check that an unsigned parameter does not receive a negative
1459 // value.
1460 if (IntegerType->isUnsignedIntegerType()
1461 && (Value.isSigned() && Value.isNegative())) {
1462 Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_negative)
1463 << Value.toString(10) << Param->getType()
1464 << Arg->getSourceRange();
1465 Diag(Param->getLocation(), diag::note_template_param_here);
1466 return true;
1467 }
1468
1469 // Check that we don't overflow the template parameter type.
1470 unsigned AllowedBits = Context.getTypeSize(IntegerType);
1471 if (Value.getActiveBits() > AllowedBits) {
1472 Diag(Arg->getSourceRange().getBegin(),
1473 diag::err_template_arg_too_large)
1474 << Value.toString(10) << Param->getType()
1475 << Arg->getSourceRange();
1476 Diag(Param->getLocation(), diag::note_template_param_here);
1477 return true;
1478 }
1479
1480 if (Value.getBitWidth() != AllowedBits)
1481 Value.extOrTrunc(AllowedBits);
1482 Value.setIsSigned(IntegerType->isSignedIntegerType());
1483 }
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001484
1485 if (Converted) {
1486 // Add the value of this argument to the list of converted
1487 // arguments. We use the bitwidth and signedness of the template
1488 // parameter.
Douglas Gregorba498172009-03-13 21:01:28 +00001489 if (Arg->isValueDependent()) {
1490 // The argument is value-dependent. Create a new
1491 // TemplateArgument with the converted expression.
1492 Converted->push_back(TemplateArgument(Arg));
1493 return false;
1494 }
1495
Douglas Gregor5b0f7522009-03-14 00:03:48 +00001496 Converted->push_back(TemplateArgument(StartLoc, Value,
Sebastian Redl599fe7c2009-05-27 19:21:29 +00001497 ParamType->isEnumeralType() ? ParamType : IntegerType));
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001498 }
1499
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001500 return false;
1501 }
Douglas Gregora35284b2009-02-11 00:19:33 +00001502
Douglas Gregorb86b0572009-02-11 01:18:59 +00001503 // Handle pointer-to-function, reference-to-function, and
1504 // pointer-to-member-function all in (roughly) the same way.
1505 if (// -- For a non-type template-parameter of type pointer to
1506 // function, only the function-to-pointer conversion (4.3) is
1507 // applied. If the template-argument represents a set of
1508 // overloaded functions (or a pointer to such), the matching
1509 // function is selected from the set (13.4).
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001510 // In C++0x, any std::nullptr_t value can be converted.
Douglas Gregorb86b0572009-02-11 01:18:59 +00001511 (ParamType->isPointerType() &&
1512 ParamType->getAsPointerType()->getPointeeType()->isFunctionType()) ||
1513 // -- For a non-type template-parameter of type reference to
1514 // function, no conversions apply. If the template-argument
1515 // represents a set of overloaded functions, the matching
1516 // function is selected from the set (13.4).
1517 (ParamType->isReferenceType() &&
1518 ParamType->getAsReferenceType()->getPointeeType()->isFunctionType()) ||
1519 // -- For a non-type template-parameter of type pointer to
1520 // member function, no conversions apply. If the
1521 // template-argument represents a set of overloaded member
1522 // functions, the matching member function is selected from
1523 // the set (13.4).
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001524 // Again, C++0x allows a std::nullptr_t value.
Douglas Gregorb86b0572009-02-11 01:18:59 +00001525 (ParamType->isMemberPointerType() &&
1526 ParamType->getAsMemberPointerType()->getPointeeType()
1527 ->isFunctionType())) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001528 if (Context.hasSameUnqualifiedType(ArgType,
1529 ParamType.getNonReferenceType())) {
Douglas Gregora35284b2009-02-11 00:19:33 +00001530 // We don't have to do anything: the types already match.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001531 } else if (ArgType->isNullPtrType() && (ParamType->isPointerType() ||
1532 ParamType->isMemberPointerType())) {
1533 ArgType = ParamType;
1534 ImpCastExprToType(Arg, ParamType);
Douglas Gregorb86b0572009-02-11 01:18:59 +00001535 } else if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregora35284b2009-02-11 00:19:33 +00001536 ArgType = Context.getPointerType(ArgType);
1537 ImpCastExprToType(Arg, ArgType);
1538 } else if (FunctionDecl *Fn
1539 = ResolveAddressOfOverloadedFunction(Arg, ParamType, true)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001540 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
1541 return true;
1542
Douglas Gregora35284b2009-02-11 00:19:33 +00001543 FixOverloadedFunctionReference(Arg, Fn);
1544 ArgType = Arg->getType();
Douglas Gregorb86b0572009-02-11 01:18:59 +00001545 if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregora35284b2009-02-11 00:19:33 +00001546 ArgType = Context.getPointerType(Arg->getType());
1547 ImpCastExprToType(Arg, ArgType);
1548 }
1549 }
1550
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001551 if (!Context.hasSameUnqualifiedType(ArgType,
1552 ParamType.getNonReferenceType())) {
Douglas Gregora35284b2009-02-11 00:19:33 +00001553 // We can't perform this conversion.
1554 Diag(Arg->getSourceRange().getBegin(),
1555 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00001556 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregora35284b2009-02-11 00:19:33 +00001557 Diag(Param->getLocation(), diag::note_template_param_here);
1558 return true;
1559 }
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001560
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001561 if (ParamType->isMemberPointerType()) {
1562 NamedDecl *Member = 0;
1563 if (CheckTemplateArgumentPointerToMember(Arg, Member))
1564 return true;
1565
Douglas Gregor7da97d02009-05-10 22:57:19 +00001566 if (Converted) {
Douglas Gregor92d50772009-05-10 23:27:08 +00001567 Member = cast_or_null<NamedDecl>(Context.getCanonicalDecl(Member));
Douglas Gregor40808ce2009-03-09 23:48:35 +00001568 Converted->push_back(TemplateArgument(StartLoc, Member));
Douglas Gregor7da97d02009-05-10 22:57:19 +00001569 }
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001570
1571 return false;
1572 }
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001573
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001574 NamedDecl *Entity = 0;
1575 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1576 return true;
1577
Douglas Gregor7da97d02009-05-10 22:57:19 +00001578 if (Converted) {
Douglas Gregor92d50772009-05-10 23:27:08 +00001579 Entity = cast_or_null<NamedDecl>(Context.getCanonicalDecl(Entity));
Douglas Gregor40808ce2009-03-09 23:48:35 +00001580 Converted->push_back(TemplateArgument(StartLoc, Entity));
Douglas Gregor7da97d02009-05-10 22:57:19 +00001581 }
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001582 return false;
Douglas Gregora35284b2009-02-11 00:19:33 +00001583 }
1584
Chris Lattnerfe90de72009-02-20 21:37:53 +00001585 if (ParamType->isPointerType()) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00001586 // -- for a non-type template-parameter of type pointer to
1587 // object, qualification conversions (4.4) and the
1588 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001589 // C++0x also allows a value of std::nullptr_t.
Douglas Gregorbad0e652009-03-24 20:32:41 +00001590 assert(ParamType->getAsPointerType()->getPointeeType()->isObjectType() &&
Douglas Gregorb86b0572009-02-11 01:18:59 +00001591 "Only object pointers allowed here");
Douglas Gregorf684e6e2009-02-11 00:44:29 +00001592
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001593 if (ArgType->isNullPtrType()) {
1594 ArgType = ParamType;
1595 ImpCastExprToType(Arg, ParamType);
1596 } else if (ArgType->isArrayType()) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00001597 ArgType = Context.getArrayDecayedType(ArgType);
1598 ImpCastExprToType(Arg, ArgType);
Douglas Gregorf684e6e2009-02-11 00:44:29 +00001599 }
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001600
Douglas Gregorb86b0572009-02-11 01:18:59 +00001601 if (IsQualificationConversion(ArgType, ParamType)) {
1602 ArgType = ParamType;
1603 ImpCastExprToType(Arg, ParamType);
1604 }
1605
Douglas Gregor8e6563b2009-02-11 18:22:40 +00001606 if (!Context.hasSameUnqualifiedType(ArgType, ParamType)) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00001607 // We can't perform this conversion.
1608 Diag(Arg->getSourceRange().getBegin(),
1609 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00001610 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregorb86b0572009-02-11 01:18:59 +00001611 Diag(Param->getLocation(), diag::note_template_param_here);
1612 return true;
1613 }
1614
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001615 NamedDecl *Entity = 0;
1616 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1617 return true;
1618
Douglas Gregor7da97d02009-05-10 22:57:19 +00001619 if (Converted) {
Douglas Gregor92d50772009-05-10 23:27:08 +00001620 Entity = cast_or_null<NamedDecl>(Context.getCanonicalDecl(Entity));
Douglas Gregor40808ce2009-03-09 23:48:35 +00001621 Converted->push_back(TemplateArgument(StartLoc, Entity));
Douglas Gregor7da97d02009-05-10 22:57:19 +00001622 }
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001623
1624 return false;
Douglas Gregorf684e6e2009-02-11 00:44:29 +00001625 }
Douglas Gregorb86b0572009-02-11 01:18:59 +00001626
1627 if (const ReferenceType *ParamRefType = ParamType->getAsReferenceType()) {
1628 // -- For a non-type template-parameter of type reference to
1629 // object, no conversions apply. The type referred to by the
1630 // reference may be more cv-qualified than the (otherwise
1631 // identical) type of the template-argument. The
1632 // template-parameter is bound directly to the
1633 // template-argument, which must be an lvalue.
Douglas Gregorbad0e652009-03-24 20:32:41 +00001634 assert(ParamRefType->getPointeeType()->isObjectType() &&
Douglas Gregorb86b0572009-02-11 01:18:59 +00001635 "Only object references allowed here");
Douglas Gregorf684e6e2009-02-11 00:44:29 +00001636
Douglas Gregor8e6563b2009-02-11 18:22:40 +00001637 if (!Context.hasSameUnqualifiedType(ParamRefType->getPointeeType(), ArgType)) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00001638 Diag(Arg->getSourceRange().getBegin(),
1639 diag::err_template_arg_no_ref_bind)
Douglas Gregor2943aed2009-03-03 04:44:36 +00001640 << InstantiatedParamType << Arg->getType()
Douglas Gregorb86b0572009-02-11 01:18:59 +00001641 << Arg->getSourceRange();
1642 Diag(Param->getLocation(), diag::note_template_param_here);
1643 return true;
1644 }
1645
1646 unsigned ParamQuals
1647 = Context.getCanonicalType(ParamType).getCVRQualifiers();
1648 unsigned ArgQuals = Context.getCanonicalType(ArgType).getCVRQualifiers();
1649
1650 if ((ParamQuals | ArgQuals) != ParamQuals) {
1651 Diag(Arg->getSourceRange().getBegin(),
1652 diag::err_template_arg_ref_bind_ignores_quals)
Douglas Gregor2943aed2009-03-03 04:44:36 +00001653 << InstantiatedParamType << Arg->getType()
Douglas Gregorb86b0572009-02-11 01:18:59 +00001654 << Arg->getSourceRange();
1655 Diag(Param->getLocation(), diag::note_template_param_here);
1656 return true;
1657 }
1658
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001659 NamedDecl *Entity = 0;
1660 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1661 return true;
1662
Douglas Gregor7da97d02009-05-10 22:57:19 +00001663 if (Converted) {
1664 Entity = cast<NamedDecl>(Context.getCanonicalDecl(Entity));
Douglas Gregor40808ce2009-03-09 23:48:35 +00001665 Converted->push_back(TemplateArgument(StartLoc, Entity));
Douglas Gregor7da97d02009-05-10 22:57:19 +00001666 }
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001667
1668 return false;
Douglas Gregorb86b0572009-02-11 01:18:59 +00001669 }
Douglas Gregor658bbb52009-02-11 16:16:59 +00001670
1671 // -- For a non-type template-parameter of type pointer to data
1672 // member, qualification conversions (4.4) are applied.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001673 // C++0x allows std::nullptr_t values.
Douglas Gregor658bbb52009-02-11 16:16:59 +00001674 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
1675
Douglas Gregor8e6563b2009-02-11 18:22:40 +00001676 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
Douglas Gregor658bbb52009-02-11 16:16:59 +00001677 // Types match exactly: nothing more to do here.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001678 } else if (ArgType->isNullPtrType()) {
1679 ImpCastExprToType(Arg, ParamType);
Douglas Gregor658bbb52009-02-11 16:16:59 +00001680 } else if (IsQualificationConversion(ArgType, ParamType)) {
1681 ImpCastExprToType(Arg, ParamType);
1682 } else {
1683 // We can't perform this conversion.
1684 Diag(Arg->getSourceRange().getBegin(),
1685 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00001686 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor658bbb52009-02-11 16:16:59 +00001687 Diag(Param->getLocation(), diag::note_template_param_here);
1688 return true;
1689 }
1690
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001691 NamedDecl *Member = 0;
1692 if (CheckTemplateArgumentPointerToMember(Arg, Member))
1693 return true;
1694
Douglas Gregor7da97d02009-05-10 22:57:19 +00001695 if (Converted) {
Douglas Gregor92d50772009-05-10 23:27:08 +00001696 Member = cast_or_null<NamedDecl>(Context.getCanonicalDecl(Member));
Douglas Gregor40808ce2009-03-09 23:48:35 +00001697 Converted->push_back(TemplateArgument(StartLoc, Member));
Douglas Gregor7da97d02009-05-10 22:57:19 +00001698 }
1699
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001700 return false;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001701}
1702
1703/// \brief Check a template argument against its corresponding
1704/// template template parameter.
1705///
1706/// This routine implements the semantics of C++ [temp.arg.template].
1707/// It returns true if an error occurred, and false otherwise.
1708bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
1709 DeclRefExpr *Arg) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00001710 assert(isa<TemplateDecl>(Arg->getDecl()) && "Only template decls allowed");
1711 TemplateDecl *Template = cast<TemplateDecl>(Arg->getDecl());
1712
1713 // C++ [temp.arg.template]p1:
1714 // A template-argument for a template template-parameter shall be
1715 // the name of a class template, expressed as id-expression. Only
1716 // primary class templates are considered when matching the
1717 // template template argument with the corresponding parameter;
1718 // partial specializations are not considered even if their
1719 // parameter lists match that of the template template parameter.
1720 if (!isa<ClassTemplateDecl>(Template)) {
1721 assert(isa<FunctionTemplateDecl>(Template) &&
1722 "Only function templates are possible here");
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001723 Diag(Arg->getSourceRange().getBegin(),
1724 diag::note_template_arg_refers_here_func)
Douglas Gregordd0574e2009-02-10 00:24:35 +00001725 << Template;
1726 }
1727
1728 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
1729 Param->getTemplateParameters(),
1730 true, true,
1731 Arg->getSourceRange().getBegin());
Douglas Gregorc15cb382009-02-09 23:23:08 +00001732}
1733
Douglas Gregorddc29e12009-02-06 22:42:48 +00001734/// \brief Determine whether the given template parameter lists are
1735/// equivalent.
1736///
1737/// \param New The new template parameter list, typically written in the
1738/// source code as part of a new template declaration.
1739///
1740/// \param Old The old template parameter list, typically found via
1741/// name lookup of the template declared with this template parameter
1742/// list.
1743///
1744/// \param Complain If true, this routine will produce a diagnostic if
1745/// the template parameter lists are not equivalent.
1746///
Douglas Gregordd0574e2009-02-10 00:24:35 +00001747/// \param IsTemplateTemplateParm If true, this routine is being
1748/// called to compare the template parameter lists of a template
1749/// template parameter.
1750///
1751/// \param TemplateArgLoc If this source location is valid, then we
1752/// are actually checking the template parameter list of a template
1753/// argument (New) against the template parameter list of its
1754/// corresponding template template parameter (Old). We produce
1755/// slightly different diagnostics in this scenario.
1756///
Douglas Gregorddc29e12009-02-06 22:42:48 +00001757/// \returns True if the template parameter lists are equal, false
1758/// otherwise.
1759bool
1760Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
1761 TemplateParameterList *Old,
1762 bool Complain,
Douglas Gregordd0574e2009-02-10 00:24:35 +00001763 bool IsTemplateTemplateParm,
1764 SourceLocation TemplateArgLoc) {
Douglas Gregorddc29e12009-02-06 22:42:48 +00001765 if (Old->size() != New->size()) {
1766 if (Complain) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00001767 unsigned NextDiag = diag::err_template_param_list_different_arity;
1768 if (TemplateArgLoc.isValid()) {
1769 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
1770 NextDiag = diag::note_template_param_list_different_arity;
1771 }
1772 Diag(New->getTemplateLoc(), NextDiag)
1773 << (New->size() > Old->size())
1774 << IsTemplateTemplateParm
1775 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
Douglas Gregorddc29e12009-02-06 22:42:48 +00001776 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
1777 << IsTemplateTemplateParm
1778 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
1779 }
1780
1781 return false;
1782 }
1783
1784 for (TemplateParameterList::iterator OldParm = Old->begin(),
1785 OldParmEnd = Old->end(), NewParm = New->begin();
1786 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
1787 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00001788 unsigned NextDiag = diag::err_template_param_different_kind;
1789 if (TemplateArgLoc.isValid()) {
1790 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
1791 NextDiag = diag::note_template_param_different_kind;
1792 }
1793 Diag((*NewParm)->getLocation(), NextDiag)
Douglas Gregorddc29e12009-02-06 22:42:48 +00001794 << IsTemplateTemplateParm;
1795 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
1796 << IsTemplateTemplateParm;
1797 return false;
1798 }
1799
1800 if (isa<TemplateTypeParmDecl>(*OldParm)) {
1801 // Okay; all template type parameters are equivalent (since we
Douglas Gregordd0574e2009-02-10 00:24:35 +00001802 // know we're at the same index).
1803#if 0
Mike Stump390b4cc2009-05-16 07:39:55 +00001804 // FIXME: Enable this code in debug mode *after* we properly go through
1805 // and "instantiate" the template parameter lists of template template
1806 // parameters. It's only after this instantiation that (1) any dependent
1807 // types within the template parameter list of the template template
1808 // parameter can be checked, and (2) the template type parameter depths
Douglas Gregordd0574e2009-02-10 00:24:35 +00001809 // will match up.
Douglas Gregorddc29e12009-02-06 22:42:48 +00001810 QualType OldParmType
1811 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*OldParm));
1812 QualType NewParmType
1813 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*NewParm));
1814 assert(Context.getCanonicalType(OldParmType) ==
1815 Context.getCanonicalType(NewParmType) &&
1816 "type parameter mismatch?");
1817#endif
1818 } else if (NonTypeTemplateParmDecl *OldNTTP
1819 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
1820 // The types of non-type template parameters must agree.
1821 NonTypeTemplateParmDecl *NewNTTP
1822 = cast<NonTypeTemplateParmDecl>(*NewParm);
1823 if (Context.getCanonicalType(OldNTTP->getType()) !=
1824 Context.getCanonicalType(NewNTTP->getType())) {
1825 if (Complain) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00001826 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
1827 if (TemplateArgLoc.isValid()) {
1828 Diag(TemplateArgLoc,
1829 diag::err_template_arg_template_params_mismatch);
1830 NextDiag = diag::note_template_nontype_parm_different_type;
1831 }
1832 Diag(NewNTTP->getLocation(), NextDiag)
Douglas Gregorddc29e12009-02-06 22:42:48 +00001833 << NewNTTP->getType()
1834 << IsTemplateTemplateParm;
1835 Diag(OldNTTP->getLocation(),
1836 diag::note_template_nontype_parm_prev_declaration)
1837 << OldNTTP->getType();
1838 }
1839 return false;
1840 }
1841 } else {
1842 // The template parameter lists of template template
1843 // parameters must agree.
1844 // FIXME: Could we perform a faster "type" comparison here?
1845 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
1846 "Only template template parameters handled here");
1847 TemplateTemplateParmDecl *OldTTP
1848 = cast<TemplateTemplateParmDecl>(*OldParm);
1849 TemplateTemplateParmDecl *NewTTP
1850 = cast<TemplateTemplateParmDecl>(*NewParm);
1851 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
1852 OldTTP->getTemplateParameters(),
1853 Complain,
Douglas Gregordd0574e2009-02-10 00:24:35 +00001854 /*IsTemplateTemplateParm=*/true,
1855 TemplateArgLoc))
Douglas Gregorddc29e12009-02-06 22:42:48 +00001856 return false;
1857 }
1858 }
1859
1860 return true;
1861}
1862
1863/// \brief Check whether a template can be declared within this scope.
1864///
1865/// If the template declaration is valid in this scope, returns
1866/// false. Otherwise, issues a diagnostic and returns true.
1867bool
1868Sema::CheckTemplateDeclScope(Scope *S,
1869 MultiTemplateParamsArg &TemplateParameterLists) {
1870 assert(TemplateParameterLists.size() > 0 && "Not a template");
1871
1872 // Find the nearest enclosing declaration scope.
1873 while ((S->getFlags() & Scope::DeclScope) == 0 ||
1874 (S->getFlags() & Scope::TemplateParamScope) != 0)
1875 S = S->getParent();
1876
1877 TemplateParameterList *TemplateParams =
1878 static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
1879 SourceLocation TemplateLoc = TemplateParams->getTemplateLoc();
1880 SourceRange TemplateRange
1881 = SourceRange(TemplateLoc, TemplateParams->getRAngleLoc());
1882
1883 // C++ [temp]p2:
1884 // A template-declaration can appear only as a namespace scope or
1885 // class scope declaration.
1886 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
1887 while (Ctx && isa<LinkageSpecDecl>(Ctx)) {
1888 if (cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
1889 return Diag(TemplateLoc, diag::err_template_linkage)
1890 << TemplateRange;
1891
1892 Ctx = Ctx->getParent();
1893 }
1894
1895 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
1896 return false;
1897
1898 return Diag(TemplateLoc, diag::err_template_outside_namespace_or_class_scope)
1899 << TemplateRange;
1900}
Douglas Gregorcc636682009-02-17 23:15:12 +00001901
Douglas Gregorff668032009-05-13 18:28:20 +00001902/// \brief Check whether a class template specialization or explicit
1903/// instantiation in the current context is well-formed.
Douglas Gregor88b70942009-02-25 22:02:03 +00001904///
Douglas Gregorff668032009-05-13 18:28:20 +00001905/// This routine determines whether a class template specialization or
1906/// explicit instantiation can be declared in the current context
1907/// (C++ [temp.expl.spec]p2, C++0x [temp.explicit]p2) and emits
1908/// appropriate diagnostics if there was an error. It returns true if
1909// there was an error that we cannot recover from, and false otherwise.
Douglas Gregor88b70942009-02-25 22:02:03 +00001910bool
1911Sema::CheckClassTemplateSpecializationScope(ClassTemplateDecl *ClassTemplate,
1912 ClassTemplateSpecializationDecl *PrevDecl,
1913 SourceLocation TemplateNameLoc,
Douglas Gregorff668032009-05-13 18:28:20 +00001914 SourceRange ScopeSpecifierRange,
1915 bool ExplicitInstantiation) {
Douglas Gregor88b70942009-02-25 22:02:03 +00001916 // C++ [temp.expl.spec]p2:
1917 // An explicit specialization shall be declared in the namespace
1918 // of which the template is a member, or, for member templates, in
1919 // the namespace of which the enclosing class or enclosing class
1920 // template is a member. An explicit specialization of a member
1921 // function, member class or static data member of a class
1922 // template shall be declared in the namespace of which the class
1923 // template is a member. Such a declaration may also be a
1924 // definition. If the declaration is not a definition, the
1925 // specialization may be defined later in the name- space in which
1926 // the explicit specialization was declared, or in a namespace
1927 // that encloses the one in which the explicit specialization was
1928 // declared.
1929 if (CurContext->getLookupContext()->isFunctionOrMethod()) {
1930 Diag(TemplateNameLoc, diag::err_template_spec_decl_function_scope)
Douglas Gregorff668032009-05-13 18:28:20 +00001931 << ExplicitInstantiation << ClassTemplate;
Douglas Gregor88b70942009-02-25 22:02:03 +00001932 return true;
1933 }
1934
1935 DeclContext *DC = CurContext->getEnclosingNamespaceContext();
1936 DeclContext *TemplateContext
1937 = ClassTemplate->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregorff668032009-05-13 18:28:20 +00001938 if ((!PrevDecl || PrevDecl->getSpecializationKind() == TSK_Undeclared) &&
1939 !ExplicitInstantiation) {
Douglas Gregor88b70942009-02-25 22:02:03 +00001940 // There is no prior declaration of this entity, so this
1941 // specialization must be in the same context as the template
1942 // itself.
1943 if (DC != TemplateContext) {
1944 if (isa<TranslationUnitDecl>(TemplateContext))
1945 Diag(TemplateNameLoc, diag::err_template_spec_decl_out_of_scope_global)
1946 << ClassTemplate << ScopeSpecifierRange;
1947 else if (isa<NamespaceDecl>(TemplateContext))
1948 Diag(TemplateNameLoc, diag::err_template_spec_decl_out_of_scope)
1949 << ClassTemplate << cast<NamedDecl>(TemplateContext)
1950 << ScopeSpecifierRange;
1951
1952 Diag(ClassTemplate->getLocation(), diag::note_template_decl_here);
1953 }
1954
1955 return false;
1956 }
1957
1958 // We have a previous declaration of this entity. Make sure that
1959 // this redeclaration (or definition) occurs in an enclosing namespace.
1960 if (!CurContext->Encloses(TemplateContext)) {
Mike Stump390b4cc2009-05-16 07:39:55 +00001961 // FIXME: In C++98, we would like to turn these errors into warnings,
1962 // dependent on a -Wc++0x flag.
Douglas Gregorff668032009-05-13 18:28:20 +00001963 bool SuppressedDiag = false;
1964 if (isa<TranslationUnitDecl>(TemplateContext)) {
1965 if (!ExplicitInstantiation || getLangOptions().CPlusPlus0x)
1966 Diag(TemplateNameLoc, diag::err_template_spec_redecl_global_scope)
1967 << ExplicitInstantiation << ClassTemplate << ScopeSpecifierRange;
1968 else
1969 SuppressedDiag = true;
1970 } else if (isa<NamespaceDecl>(TemplateContext)) {
1971 if (!ExplicitInstantiation || getLangOptions().CPlusPlus0x)
1972 Diag(TemplateNameLoc, diag::err_template_spec_redecl_out_of_scope)
1973 << ExplicitInstantiation << ClassTemplate
1974 << cast<NamedDecl>(TemplateContext) << ScopeSpecifierRange;
1975 else
1976 SuppressedDiag = true;
1977 }
Douglas Gregor88b70942009-02-25 22:02:03 +00001978
Douglas Gregorff668032009-05-13 18:28:20 +00001979 if (!SuppressedDiag)
1980 Diag(ClassTemplate->getLocation(), diag::note_template_decl_here);
Douglas Gregor88b70942009-02-25 22:02:03 +00001981 }
1982
1983 return false;
1984}
1985
Douglas Gregor212e81c2009-03-25 00:13:59 +00001986Sema::DeclResult
Douglas Gregorcc636682009-02-17 23:15:12 +00001987Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec, TagKind TK,
1988 SourceLocation KWLoc,
1989 const CXXScopeSpec &SS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00001990 TemplateTy TemplateD,
Douglas Gregorcc636682009-02-17 23:15:12 +00001991 SourceLocation TemplateNameLoc,
1992 SourceLocation LAngleLoc,
Douglas Gregor40808ce2009-03-09 23:48:35 +00001993 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregorcc636682009-02-17 23:15:12 +00001994 SourceLocation *TemplateArgLocs,
1995 SourceLocation RAngleLoc,
1996 AttributeList *Attr,
1997 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregorcc636682009-02-17 23:15:12 +00001998 // Find the class template we're specializing
Douglas Gregor7532dc62009-03-30 22:58:21 +00001999 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Douglas Gregorcc636682009-02-17 23:15:12 +00002000 ClassTemplateDecl *ClassTemplate
Douglas Gregor7532dc62009-03-30 22:58:21 +00002001 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
Douglas Gregorcc636682009-02-17 23:15:12 +00002002
Douglas Gregor88b70942009-02-25 22:02:03 +00002003 // Check the validity of the template headers that introduce this
2004 // template.
Douglas Gregor6bc9f7e2009-02-25 22:18:32 +00002005 // FIXME: Once we have member templates, we'll need to check
2006 // C++ [temp.expl.spec]p17-18, where we could have multiple levels of
2007 // template<> headers.
Douglas Gregor4b2d3f72009-02-26 21:00:50 +00002008 if (TemplateParameterLists.size() == 0)
2009 Diag(KWLoc, diag::err_template_spec_needs_header)
Douglas Gregorb2fb6de2009-02-27 17:53:17 +00002010 << CodeModificationHint::CreateInsertion(KWLoc, "template<> ");
Douglas Gregor4b2d3f72009-02-26 21:00:50 +00002011 else {
Douglas Gregor88b70942009-02-25 22:02:03 +00002012 TemplateParameterList *TemplateParams
2013 = static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
Chris Lattnerb28317a2009-03-28 19:18:32 +00002014 if (TemplateParameterLists.size() > 1) {
2015 Diag(TemplateParams->getTemplateLoc(),
2016 diag::err_template_spec_extra_headers);
2017 return true;
2018 }
Douglas Gregor88b70942009-02-25 22:02:03 +00002019
Chris Lattnerb28317a2009-03-28 19:18:32 +00002020 if (TemplateParams->size() > 0) {
Douglas Gregor88b70942009-02-25 22:02:03 +00002021 // FIXME: No support for class template partial specialization.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002022 Diag(TemplateParams->getTemplateLoc(), diag::unsup_template_partial_spec);
2023 return true;
2024 }
Douglas Gregor88b70942009-02-25 22:02:03 +00002025 }
2026
Douglas Gregorcc636682009-02-17 23:15:12 +00002027 // Check that the specialization uses the same tag kind as the
2028 // original template.
2029 TagDecl::TagKind Kind;
2030 switch (TagSpec) {
2031 default: assert(0 && "Unknown tag type!");
2032 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2033 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2034 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2035 }
Douglas Gregor501c5ce2009-05-14 16:41:31 +00002036 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
2037 Kind, KWLoc,
2038 *ClassTemplate->getIdentifier())) {
Douglas Gregora3a83512009-04-01 23:51:29 +00002039 Diag(KWLoc, diag::err_use_with_wrong_tag)
2040 << ClassTemplate
2041 << CodeModificationHint::CreateReplacement(KWLoc,
2042 ClassTemplate->getTemplatedDecl()->getKindName());
Douglas Gregorcc636682009-02-17 23:15:12 +00002043 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
2044 diag::note_previous_use);
2045 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
2046 }
2047
Douglas Gregor40808ce2009-03-09 23:48:35 +00002048 // Translate the parser's template argument list in our AST format.
2049 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
2050 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
2051
Douglas Gregorcc636682009-02-17 23:15:12 +00002052 // Check that the template argument list is well-formed for this
2053 // template.
2054 llvm::SmallVector<TemplateArgument, 16> ConvertedTemplateArgs;
2055 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
Douglas Gregor40808ce2009-03-09 23:48:35 +00002056 &TemplateArgs[0], TemplateArgs.size(),
2057 RAngleLoc, ConvertedTemplateArgs))
Douglas Gregor212e81c2009-03-25 00:13:59 +00002058 return true;
Douglas Gregorcc636682009-02-17 23:15:12 +00002059
2060 assert((ConvertedTemplateArgs.size() ==
2061 ClassTemplate->getTemplateParameters()->size()) &&
2062 "Converted template argument list is too short!");
2063
2064 // Find the class template specialization declaration that
2065 // corresponds to these arguments.
2066 llvm::FoldingSetNodeID ID;
2067 ClassTemplateSpecializationDecl::Profile(ID, &ConvertedTemplateArgs[0],
2068 ConvertedTemplateArgs.size());
2069 void *InsertPos = 0;
2070 ClassTemplateSpecializationDecl *PrevDecl
2071 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
2072
2073 ClassTemplateSpecializationDecl *Specialization = 0;
2074
Douglas Gregor88b70942009-02-25 22:02:03 +00002075 // Check whether we can declare a class template specialization in
2076 // the current scope.
2077 if (CheckClassTemplateSpecializationScope(ClassTemplate, PrevDecl,
2078 TemplateNameLoc,
Douglas Gregorff668032009-05-13 18:28:20 +00002079 SS.getRange(),
2080 /*ExplicitInstantiation=*/false))
Douglas Gregor212e81c2009-03-25 00:13:59 +00002081 return true;
Douglas Gregor88b70942009-02-25 22:02:03 +00002082
Douglas Gregorcc636682009-02-17 23:15:12 +00002083 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
2084 // Since the only prior class template specialization with these
2085 // arguments was referenced but not declared, reuse that
2086 // declaration node as our own, updating its source location to
2087 // reflect our new declaration.
Douglas Gregorcc636682009-02-17 23:15:12 +00002088 Specialization = PrevDecl;
Douglas Gregor6bc9f7e2009-02-25 22:18:32 +00002089 Specialization->setLocation(TemplateNameLoc);
Douglas Gregorcc636682009-02-17 23:15:12 +00002090 PrevDecl = 0;
2091 } else {
2092 // Create a new class template specialization declaration node for
2093 // this explicit specialization.
2094 Specialization
2095 = ClassTemplateSpecializationDecl::Create(Context,
2096 ClassTemplate->getDeclContext(),
2097 TemplateNameLoc,
2098 ClassTemplate,
2099 &ConvertedTemplateArgs[0],
2100 ConvertedTemplateArgs.size(),
2101 PrevDecl);
2102
2103 if (PrevDecl) {
2104 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
2105 ClassTemplate->getSpecializations().GetOrInsertNode(Specialization);
2106 } else {
2107 ClassTemplate->getSpecializations().InsertNode(Specialization,
2108 InsertPos);
2109 }
2110 }
2111
2112 // Note that this is an explicit specialization.
2113 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
2114
2115 // Check that this isn't a redefinition of this specialization.
2116 if (TK == TK_Definition) {
2117 if (RecordDecl *Def = Specialization->getDefinition(Context)) {
Mike Stump390b4cc2009-05-16 07:39:55 +00002118 // FIXME: Should also handle explicit specialization after implicit
2119 // instantiation with a special diagnostic.
Douglas Gregorcc636682009-02-17 23:15:12 +00002120 SourceRange Range(TemplateNameLoc, RAngleLoc);
2121 Diag(TemplateNameLoc, diag::err_redefinition)
2122 << Specialization << Range;
2123 Diag(Def->getLocation(), diag::note_previous_definition);
2124 Specialization->setInvalidDecl();
Douglas Gregor212e81c2009-03-25 00:13:59 +00002125 return true;
Douglas Gregorcc636682009-02-17 23:15:12 +00002126 }
2127 }
2128
Douglas Gregorfc705b82009-02-26 22:19:44 +00002129 // Build the fully-sugared type for this class template
2130 // specialization as the user wrote in the specialization
2131 // itself. This means that we'll pretty-print the type retrieved
2132 // from the specialization's declaration the way that the user
2133 // actually wrote the specialization, rather than formatting the
2134 // name based on the "canonical" representation used to store the
2135 // template arguments in the specialization.
Douglas Gregore6258932009-03-19 00:39:20 +00002136 QualType WrittenTy
Douglas Gregor7532dc62009-03-30 22:58:21 +00002137 = Context.getTemplateSpecializationType(Name,
2138 &TemplateArgs[0],
2139 TemplateArgs.size(),
Douglas Gregore6258932009-03-19 00:39:20 +00002140 Context.getTypeDeclType(Specialization));
Douglas Gregor7532dc62009-03-30 22:58:21 +00002141 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregor40808ce2009-03-09 23:48:35 +00002142 TemplateArgsIn.release();
Douglas Gregorcc636682009-02-17 23:15:12 +00002143
Douglas Gregor6bc9f7e2009-02-25 22:18:32 +00002144 // C++ [temp.expl.spec]p9:
2145 // A template explicit specialization is in the scope of the
2146 // namespace in which the template was defined.
2147 //
2148 // We actually implement this paragraph where we set the semantic
2149 // context (in the creation of the ClassTemplateSpecializationDecl),
2150 // but we also maintain the lexical context where the actual
2151 // definition occurs.
Douglas Gregorcc636682009-02-17 23:15:12 +00002152 Specialization->setLexicalDeclContext(CurContext);
2153
2154 // We may be starting the definition of this specialization.
2155 if (TK == TK_Definition)
2156 Specialization->startDefinition();
2157
2158 // Add the specialization into its lexical context, so that it can
2159 // be seen when iterating through the list of declarations in that
2160 // context. However, specializations are not found by name lookup.
Douglas Gregor6ab35242009-04-09 21:40:53 +00002161 CurContext->addDecl(Context, Specialization);
Chris Lattnerb28317a2009-03-28 19:18:32 +00002162 return DeclPtrTy::make(Specialization);
Douglas Gregorcc636682009-02-17 23:15:12 +00002163}
Douglas Gregord57959a2009-03-27 23:10:48 +00002164
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002165// Explicit instantiation of a class template specialization
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002166Sema::DeclResult
2167Sema::ActOnExplicitInstantiation(Scope *S, SourceLocation TemplateLoc,
2168 unsigned TagSpec,
2169 SourceLocation KWLoc,
2170 const CXXScopeSpec &SS,
2171 TemplateTy TemplateD,
2172 SourceLocation TemplateNameLoc,
2173 SourceLocation LAngleLoc,
2174 ASTTemplateArgsPtr TemplateArgsIn,
2175 SourceLocation *TemplateArgLocs,
2176 SourceLocation RAngleLoc,
2177 AttributeList *Attr) {
2178 // Find the class template we're specializing
2179 TemplateName Name = TemplateD.getAsVal<TemplateName>();
2180 ClassTemplateDecl *ClassTemplate
2181 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
2182
2183 // Check that the specialization uses the same tag kind as the
2184 // original template.
2185 TagDecl::TagKind Kind;
2186 switch (TagSpec) {
2187 default: assert(0 && "Unknown tag type!");
2188 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2189 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2190 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2191 }
Douglas Gregor501c5ce2009-05-14 16:41:31 +00002192 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
2193 Kind, KWLoc,
2194 *ClassTemplate->getIdentifier())) {
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002195 Diag(KWLoc, diag::err_use_with_wrong_tag)
2196 << ClassTemplate
2197 << CodeModificationHint::CreateReplacement(KWLoc,
2198 ClassTemplate->getTemplatedDecl()->getKindName());
2199 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
2200 diag::note_previous_use);
2201 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
2202 }
2203
Douglas Gregorff668032009-05-13 18:28:20 +00002204 // C++0x [temp.explicit]p2:
2205 // [...] An explicit instantiation shall appear in an enclosing
2206 // namespace of its template. [...]
2207 //
2208 // This is C++ DR 275.
2209 if (CheckClassTemplateSpecializationScope(ClassTemplate, 0,
2210 TemplateNameLoc,
2211 SS.getRange(),
2212 /*ExplicitInstantiation=*/true))
2213 return true;
2214
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002215 // Translate the parser's template argument list in our AST format.
2216 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
2217 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
2218
2219 // Check that the template argument list is well-formed for this
2220 // template.
2221 llvm::SmallVector<TemplateArgument, 16> ConvertedTemplateArgs;
2222 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
2223 &TemplateArgs[0], TemplateArgs.size(),
2224 RAngleLoc, ConvertedTemplateArgs))
2225 return true;
2226
2227 assert((ConvertedTemplateArgs.size() ==
2228 ClassTemplate->getTemplateParameters()->size()) &&
2229 "Converted template argument list is too short!");
2230
2231 // Find the class template specialization declaration that
2232 // corresponds to these arguments.
2233 llvm::FoldingSetNodeID ID;
2234 ClassTemplateSpecializationDecl::Profile(ID, &ConvertedTemplateArgs[0],
2235 ConvertedTemplateArgs.size());
2236 void *InsertPos = 0;
2237 ClassTemplateSpecializationDecl *PrevDecl
2238 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
2239
2240 ClassTemplateSpecializationDecl *Specialization = 0;
2241
Douglas Gregorff668032009-05-13 18:28:20 +00002242 bool SpecializationRequiresInstantiation = true;
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002243 if (PrevDecl) {
Douglas Gregorff668032009-05-13 18:28:20 +00002244 if (PrevDecl->getSpecializationKind() == TSK_ExplicitInstantiation) {
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002245 // This particular specialization has already been declared or
2246 // instantiated. We cannot explicitly instantiate it.
Douglas Gregorff668032009-05-13 18:28:20 +00002247 Diag(TemplateNameLoc, diag::err_explicit_instantiation_duplicate)
2248 << Context.getTypeDeclType(PrevDecl);
2249 Diag(PrevDecl->getLocation(),
2250 diag::note_previous_explicit_instantiation);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002251 return DeclPtrTy::make(PrevDecl);
2252 }
2253
Douglas Gregorff668032009-05-13 18:28:20 +00002254 if (PrevDecl->getSpecializationKind() == TSK_ExplicitSpecialization) {
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002255 // C++ DR 259, C++0x [temp.explicit]p4:
Douglas Gregorff668032009-05-13 18:28:20 +00002256 // For a given set of template parameters, if an explicit
2257 // instantiation of a template appears after a declaration of
2258 // an explicit specialization for that template, the explicit
2259 // instantiation has no effect.
2260 if (!getLangOptions().CPlusPlus0x) {
2261 Diag(TemplateNameLoc,
2262 diag::ext_explicit_instantiation_after_specialization)
2263 << Context.getTypeDeclType(PrevDecl);
2264 Diag(PrevDecl->getLocation(),
2265 diag::note_previous_template_specialization);
2266 }
2267
2268 // Create a new class template specialization declaration node
2269 // for this explicit specialization. This node is only used to
2270 // record the existence of this explicit instantiation for
2271 // accurate reproduction of the source code; we don't actually
2272 // use it for anything, since it is semantically irrelevant.
2273 Specialization
2274 = ClassTemplateSpecializationDecl::Create(Context,
2275 ClassTemplate->getDeclContext(),
2276 TemplateNameLoc,
2277 ClassTemplate,
2278 &ConvertedTemplateArgs[0],
2279 ConvertedTemplateArgs.size(),
2280 0);
2281 Specialization->setLexicalDeclContext(CurContext);
2282 CurContext->addDecl(Context, Specialization);
2283 return DeclPtrTy::make(Specialization);
2284 }
2285
2286 // If we have already (implicitly) instantiated this
2287 // specialization, there is less work to do.
2288 if (PrevDecl->getSpecializationKind() == TSK_ImplicitInstantiation)
2289 SpecializationRequiresInstantiation = false;
2290
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002291 // Since the only prior class template specialization with these
2292 // arguments was referenced but not declared, reuse that
2293 // declaration node as our own, updating its source location to
2294 // reflect our new declaration.
2295 Specialization = PrevDecl;
2296 Specialization->setLocation(TemplateNameLoc);
2297 PrevDecl = 0;
2298 } else {
2299 // Create a new class template specialization declaration node for
2300 // this explicit specialization.
2301 Specialization
2302 = ClassTemplateSpecializationDecl::Create(Context,
2303 ClassTemplate->getDeclContext(),
2304 TemplateNameLoc,
2305 ClassTemplate,
2306 &ConvertedTemplateArgs[0],
2307 ConvertedTemplateArgs.size(),
2308 0);
2309
2310 ClassTemplate->getSpecializations().InsertNode(Specialization,
2311 InsertPos);
2312 }
2313
2314 // Build the fully-sugared type for this explicit instantiation as
2315 // the user wrote in the explicit instantiation itself. This means
2316 // that we'll pretty-print the type retrieved from the
2317 // specialization's declaration the way that the user actually wrote
2318 // the explicit instantiation, rather than formatting the name based
2319 // on the "canonical" representation used to store the template
2320 // arguments in the specialization.
2321 QualType WrittenTy
2322 = Context.getTemplateSpecializationType(Name,
2323 &TemplateArgs[0],
2324 TemplateArgs.size(),
2325 Context.getTypeDeclType(Specialization));
2326 Specialization->setTypeAsWritten(WrittenTy);
2327 TemplateArgsIn.release();
2328
2329 // Add the explicit instantiation into its lexical context. However,
2330 // since explicit instantiations are never found by name lookup, we
2331 // just put it into the declaration context directly.
2332 Specialization->setLexicalDeclContext(CurContext);
2333 CurContext->addDecl(Context, Specialization);
2334
2335 // C++ [temp.explicit]p3:
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002336 // A definition of a class template or class member template
2337 // shall be in scope at the point of the explicit instantiation of
2338 // the class template or class member template.
2339 //
2340 // This check comes when we actually try to perform the
2341 // instantiation.
Douglas Gregore2c31ff2009-05-15 17:59:04 +00002342 if (SpecializationRequiresInstantiation)
2343 InstantiateClassTemplateSpecialization(Specialization, true);
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00002344 else // Instantiate the members of this class template specialization.
Douglas Gregore2c31ff2009-05-15 17:59:04 +00002345 InstantiateClassTemplateSpecializationMembers(TemplateLoc, Specialization);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002346
2347 return DeclPtrTy::make(Specialization);
2348}
2349
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002350// Explicit instantiation of a member class of a class template.
2351Sema::DeclResult
2352Sema::ActOnExplicitInstantiation(Scope *S, SourceLocation TemplateLoc,
2353 unsigned TagSpec,
2354 SourceLocation KWLoc,
2355 const CXXScopeSpec &SS,
2356 IdentifierInfo *Name,
2357 SourceLocation NameLoc,
2358 AttributeList *Attr) {
2359
2360 DeclPtrTy TagD = ActOnTag(S, TagSpec, Action::TK_Reference,
2361 KWLoc, SS, Name, NameLoc, Attr, AS_none);
2362 if (!TagD)
2363 return true;
2364
2365 TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
2366 if (Tag->isEnum()) {
2367 Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
2368 << Context.getTypeDeclType(Tag);
2369 return true;
2370 }
2371
Douglas Gregord0c87372009-05-27 17:30:49 +00002372 if (Tag->isInvalidDecl())
2373 return true;
2374
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002375 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
2376 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
2377 if (!Pattern) {
2378 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
2379 << Context.getTypeDeclType(Record);
2380 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
2381 return true;
2382 }
2383
2384 // C++0x [temp.explicit]p2:
2385 // [...] An explicit instantiation shall appear in an enclosing
2386 // namespace of its template. [...]
2387 //
2388 // This is C++ DR 275.
2389 if (getLangOptions().CPlusPlus0x) {
Mike Stump390b4cc2009-05-16 07:39:55 +00002390 // FIXME: In C++98, we would like to turn these errors into warnings,
2391 // dependent on a -Wc++0x flag.
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002392 DeclContext *PatternContext
2393 = Pattern->getDeclContext()->getEnclosingNamespaceContext();
2394 if (!CurContext->Encloses(PatternContext)) {
2395 Diag(TemplateLoc, diag::err_explicit_instantiation_out_of_scope)
2396 << Record << cast<NamedDecl>(PatternContext) << SS.getRange();
2397 Diag(Pattern->getLocation(), diag::note_previous_declaration);
2398 }
2399 }
2400
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002401 if (!Record->getDefinition(Context)) {
2402 // If the class has a definition, instantiate it (and all of its
2403 // members, recursively).
2404 Pattern = cast_or_null<CXXRecordDecl>(Pattern->getDefinition(Context));
2405 if (Pattern && InstantiateClass(TemplateLoc, Record, Pattern,
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002406 getTemplateInstantiationArgs(Record),
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002407 /*ExplicitInstantiation=*/true))
2408 return true;
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00002409 } else // Instantiate all of the members of class.
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002410 InstantiateClassMembers(TemplateLoc, Record,
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002411 getTemplateInstantiationArgs(Record));
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002412
Mike Stump390b4cc2009-05-16 07:39:55 +00002413 // FIXME: We don't have any representation for explicit instantiations of
2414 // member classes. Such a representation is not needed for compilation, but it
2415 // should be available for clients that want to see all of the declarations in
2416 // the source code.
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002417 return TagD;
2418}
2419
Douglas Gregord57959a2009-03-27 23:10:48 +00002420Sema::TypeResult
2421Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
2422 const IdentifierInfo &II, SourceLocation IdLoc) {
2423 NestedNameSpecifier *NNS
2424 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
2425 if (!NNS)
2426 return true;
2427
2428 QualType T = CheckTypenameType(NNS, II, SourceRange(TypenameLoc, IdLoc));
Douglas Gregor31a19b62009-04-01 21:51:26 +00002429 if (T.isNull())
2430 return true;
Douglas Gregord57959a2009-03-27 23:10:48 +00002431 return T.getAsOpaquePtr();
2432}
2433
Douglas Gregor17343172009-04-01 00:28:59 +00002434Sema::TypeResult
2435Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
2436 SourceLocation TemplateLoc, TypeTy *Ty) {
2437 QualType T = QualType::getFromOpaquePtr(Ty);
2438 NestedNameSpecifier *NNS
2439 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
2440 const TemplateSpecializationType *TemplateId
2441 = T->getAsTemplateSpecializationType();
2442 assert(TemplateId && "Expected a template specialization type");
2443
2444 if (NNS->isDependent())
2445 return Context.getTypenameType(NNS, TemplateId).getAsOpaquePtr();
2446
2447 return Context.getQualifiedNameType(NNS, T).getAsOpaquePtr();
2448}
2449
Douglas Gregord57959a2009-03-27 23:10:48 +00002450/// \brief Build the type that describes a C++ typename specifier,
2451/// e.g., "typename T::type".
2452QualType
2453Sema::CheckTypenameType(NestedNameSpecifier *NNS, const IdentifierInfo &II,
2454 SourceRange Range) {
Douglas Gregor42af25f2009-05-11 19:58:34 +00002455 CXXRecordDecl *CurrentInstantiation = 0;
2456 if (NNS->isDependent()) {
2457 CurrentInstantiation = getCurrentInstantiationOf(NNS);
Douglas Gregord57959a2009-03-27 23:10:48 +00002458
Douglas Gregor42af25f2009-05-11 19:58:34 +00002459 // If the nested-name-specifier does not refer to the current
2460 // instantiation, then build a typename type.
2461 if (!CurrentInstantiation)
2462 return Context.getTypenameType(NNS, &II);
2463 }
Douglas Gregord57959a2009-03-27 23:10:48 +00002464
Douglas Gregor42af25f2009-05-11 19:58:34 +00002465 DeclContext *Ctx = 0;
2466
2467 if (CurrentInstantiation)
2468 Ctx = CurrentInstantiation;
2469 else {
2470 CXXScopeSpec SS;
2471 SS.setScopeRep(NNS);
2472 SS.setRange(Range);
2473 if (RequireCompleteDeclContext(SS))
2474 return QualType();
2475
2476 Ctx = computeDeclContext(SS);
2477 }
Douglas Gregord57959a2009-03-27 23:10:48 +00002478 assert(Ctx && "No declaration context?");
2479
2480 DeclarationName Name(&II);
2481 LookupResult Result = LookupQualifiedName(Ctx, Name, LookupOrdinaryName,
2482 false);
2483 unsigned DiagID = 0;
2484 Decl *Referenced = 0;
2485 switch (Result.getKind()) {
2486 case LookupResult::NotFound:
2487 if (Ctx->isTranslationUnit())
2488 DiagID = diag::err_typename_nested_not_found_global;
2489 else
2490 DiagID = diag::err_typename_nested_not_found;
2491 break;
2492
2493 case LookupResult::Found:
2494 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getAsDecl())) {
2495 // We found a type. Build a QualifiedNameType, since the
2496 // typename-specifier was just sugar. FIXME: Tell
2497 // QualifiedNameType that it has a "typename" prefix.
2498 return Context.getQualifiedNameType(NNS, Context.getTypeDeclType(Type));
2499 }
2500
2501 DiagID = diag::err_typename_nested_not_type;
2502 Referenced = Result.getAsDecl();
2503 break;
2504
2505 case LookupResult::FoundOverloaded:
2506 DiagID = diag::err_typename_nested_not_type;
2507 Referenced = *Result.begin();
2508 break;
2509
2510 case LookupResult::AmbiguousBaseSubobjectTypes:
2511 case LookupResult::AmbiguousBaseSubobjects:
2512 case LookupResult::AmbiguousReference:
2513 DiagnoseAmbiguousLookup(Result, Name, Range.getEnd(), Range);
2514 return QualType();
2515 }
2516
2517 // If we get here, it's because name lookup did not find a
2518 // type. Emit an appropriate diagnostic and return an error.
2519 if (NamedDecl *NamedCtx = dyn_cast<NamedDecl>(Ctx))
2520 Diag(Range.getEnd(), DiagID) << Range << Name << NamedCtx;
2521 else
2522 Diag(Range.getEnd(), DiagID) << Range << Name;
2523 if (Referenced)
2524 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
2525 << Name;
2526 return QualType();
2527}