blob: afd801cf619df1bf9b778b706a2da6eeaa9ad354 [file] [log] [blame]
Douglas Gregordd861062008-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 Gregor74296542009-02-27 19:31:52 +00008//===----------------------------------------------------------------------===/
Douglas Gregordd861062008-12-05 18:15:24 +00009
10//
11// This file implements semantic analysis for C++ templates.
Douglas Gregor74296542009-02-27 19:31:52 +000012//===----------------------------------------------------------------------===/
Douglas Gregordd861062008-12-05 18:15:24 +000013
14#include "Sema.h"
Douglas Gregord406b032009-02-06 22:42:48 +000015#include "clang/AST/ASTContext.h"
Douglas Gregor1b21c7f2008-12-05 23:32:09 +000016#include "clang/AST/Expr.h"
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +000017#include "clang/AST/ExprCXX.h"
Douglas Gregor279272e2009-02-04 19:02:06 +000018#include "clang/AST/DeclTemplate.h"
Douglas Gregordd861062008-12-05 18:15:24 +000019#include "clang/Parse/DeclSpec.h"
20#include "clang/Basic/LangOptions.h"
21
22using namespace clang;
23
Douglas Gregor2fa10442008-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 Gregoraabb8502009-03-31 00:43:58 +000029TemplateNameKind Sema::isTemplateName(const IdentifierInfo &II, Scope *S,
Douglas Gregordd13e842009-03-30 22:58:21 +000030 TemplateTy &TemplateResult,
Douglas Gregor0c281a82009-02-25 19:37:18 +000031 const CXXScopeSpec *SS) {
Douglas Gregor09be81b2009-02-04 17:27:36 +000032 NamedDecl *IIDecl = LookupParsedName(S, SS, &II, LookupOrdinaryName);
Douglas Gregor2fa10442008-12-18 19:37:40 +000033
Douglas Gregordd13e842009-03-30 22:58:21 +000034 TemplateNameKind TNK = TNK_Non_template;
35 TemplateDecl *Template = 0;
36
Douglas Gregor2fa10442008-12-18 19:37:40 +000037 if (IIDecl) {
Douglas Gregordd13e842009-03-30 22:58:21 +000038 if ((Template = dyn_cast<TemplateDecl>(IIDecl))) {
Douglas Gregor8e458f42009-02-09 18:46:07 +000039 if (isa<FunctionTemplateDecl>(IIDecl))
Douglas Gregordd13e842009-03-30 22:58:21 +000040 TNK = TNK_Function_template;
Douglas Gregoraabb8502009-03-31 00:43:58 +000041 else if (isa<ClassTemplateDecl>(IIDecl) ||
42 isa<TemplateTemplateParmDecl>(IIDecl))
43 TNK = TNK_Type_template;
Douglas Gregordd13e842009-03-30 22:58:21 +000044 else
45 assert(false && "Unknown template declaration kind");
Douglas Gregor55216ac2009-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 Gregordd13e842009-03-30 22:58:21 +000060 if ((Template = Record->getDescribedClassTemplate()))
Douglas Gregoraabb8502009-03-31 00:43:58 +000061 TNK = TNK_Type_template;
Douglas Gregordd13e842009-03-30 22:58:21 +000062 else if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor55216ac2009-03-26 00:10:35 +000063 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
Douglas Gregordd13e842009-03-30 22:58:21 +000064 Template = Spec->getSpecializedTemplate();
Douglas Gregoraabb8502009-03-31 00:43:58 +000065 TNK = TNK_Type_template;
Douglas Gregor55216ac2009-03-26 00:10:35 +000066 }
67 }
Douglas Gregor8e458f42009-02-09 18:46:07 +000068 }
Douglas Gregor279272e2009-02-04 19:02:06 +000069
Douglas Gregor8e458f42009-02-09 18:46:07 +000070 // FIXME: What follows is a gross hack.
Douglas Gregor2fa10442008-12-18 19:37:40 +000071 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(IIDecl)) {
Douglas Gregor8e458f42009-02-09 18:46:07 +000072 if (FD->getType()->isDependentType()) {
Douglas Gregordd13e842009-03-30 22:58:21 +000073 TemplateResult = TemplateTy::make(FD);
Douglas Gregor8e458f42009-02-09 18:46:07 +000074 return TNK_Function_template;
75 }
Douglas Gregor2fa10442008-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 Gregor8e458f42009-02-09 18:46:07 +000081 if ((*F)->getType()->isDependentType()) {
Douglas Gregordd13e842009-03-30 22:58:21 +000082 TemplateResult = TemplateTy::make(Ovl);
Douglas Gregor8e458f42009-02-09 18:46:07 +000083 return TNK_Function_template;
84 }
Douglas Gregor2fa10442008-12-18 19:37:40 +000085 }
86 }
Douglas Gregordd13e842009-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 Gregor2fa10442008-12-18 19:37:40 +000099 }
Douglas Gregordd13e842009-03-30 22:58:21 +0000100 return TNK;
Douglas Gregor2fa10442008-12-18 19:37:40 +0000101}
102
Douglas Gregordd861062008-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 Gregor2715a1f2008-12-08 18:40:42 +0000108 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregordd861062008-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 Gregored3a3982009-03-03 04:44:36 +0000123/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregor279272e2009-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 Lattner5261d0c2009-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 Gregor279272e2009-02-04 19:02:06 +0000129 return Temp;
130 }
131 return 0;
132}
133
Douglas Gregordd861062008-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 Lattner5261d0c2009-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 Gregordd861062008-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 Gregor09be81b2009-02-04 17:27:36 +0000153 NamedDecl *PrevDecl = LookupName(S, ParamName, LookupTagName);
Douglas Gregor2715a1f2008-12-08 18:40:42 +0000154 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregordd861062008-12-05 18:15:24 +0000155 Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc,
156 PrevDecl);
157 }
158
Douglas Gregord406b032009-02-06 22:42:48 +0000159 SourceLocation Loc = ParamNameLoc;
160 if (!ParamName)
161 Loc = KeyLoc;
162
Douglas Gregordd861062008-12-05 18:15:24 +0000163 TemplateTypeParmDecl *Param
Douglas Gregord406b032009-02-06 22:42:48 +0000164 = TemplateTypeParmDecl::Create(Context, CurContext, Loc,
Douglas Gregor279272e2009-02-04 19:02:06 +0000165 Depth, Position, ParamName, Typename);
Douglas Gregordd861062008-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 Lattner5261d0c2009-03-28 19:18:32 +0000171 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregordd861062008-12-05 18:15:24 +0000172 IdResolver.AddDecl(Param);
173 }
174
Chris Lattner5261d0c2009-03-28 19:18:32 +0000175 return DeclPtrTy::make(Param);
Douglas Gregordd861062008-12-05 18:15:24 +0000176}
177
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000178/// ActOnTypeParameterDefault - Adds a default argument (the type
179/// Default) to the given template type parameter (TypeParam).
Chris Lattner5261d0c2009-03-28 19:18:32 +0000180void Sema::ActOnTypeParameterDefault(DeclPtrTy TypeParam,
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000181 SourceLocation EqualLoc,
182 SourceLocation DefaultLoc,
183 TypeTy *DefaultT) {
184 TemplateTypeParmDecl *Parm
Chris Lattner5261d0c2009-03-28 19:18:32 +0000185 = cast<TemplateTypeParmDecl>(TypeParam.getAs<Decl>());
Douglas Gregor9225a7e2009-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 Gregored3a3982009-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 Gregordd861062008-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 Lattner5261d0c2009-03-28 19:18:32 +0000249Sema::DeclPtrTy Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
250 unsigned Depth,
251 unsigned Position) {
Douglas Gregordd861062008-12-05 18:15:24 +0000252 QualType T = GetTypeForDeclarator(D, S);
253
Douglas Gregor279272e2009-02-04 19:02:06 +0000254 assert(S->isTemplateParamScope() &&
255 "Non-type template parameter not in template parameter scope!");
Douglas Gregordd861062008-12-05 18:15:24 +0000256 bool Invalid = false;
257
258 IdentifierInfo *ParamName = D.getIdentifier();
259 if (ParamName) {
Douglas Gregor09be81b2009-02-04 17:27:36 +0000260 NamedDecl *PrevDecl = LookupName(S, ParamName, LookupTagName);
Douglas Gregor2715a1f2008-12-08 18:40:42 +0000261 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregordd861062008-12-05 18:15:24 +0000262 Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
Douglas Gregor279272e2009-02-04 19:02:06 +0000263 PrevDecl);
Douglas Gregordd861062008-12-05 18:15:24 +0000264 }
265
Douglas Gregored3a3982009-03-03 04:44:36 +0000266 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
Douglas Gregor8b90e8e2009-03-09 16:46:39 +0000267 if (T.isNull()) {
Douglas Gregored3a3982009-03-03 04:44:36 +0000268 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregor8b90e8e2009-03-09 16:46:39 +0000269 Invalid = true;
270 }
Douglas Gregor62cdc792009-02-10 17:43:50 +0000271
Douglas Gregordd861062008-12-05 18:15:24 +0000272 NonTypeTemplateParmDecl *Param
273 = NonTypeTemplateParmDecl::Create(Context, CurContext, D.getIdentifierLoc(),
Douglas Gregor279272e2009-02-04 19:02:06 +0000274 Depth, Position, ParamName, T);
Douglas Gregordd861062008-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 Lattner5261d0c2009-03-28 19:18:32 +0000280 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregordd861062008-12-05 18:15:24 +0000281 IdResolver.AddDecl(Param);
282 }
Chris Lattner5261d0c2009-03-28 19:18:32 +0000283 return DeclPtrTy::make(Param);
Douglas Gregordd861062008-12-05 18:15:24 +0000284}
Douglas Gregor52473432008-12-24 02:52:09 +0000285
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000286/// \brief Adds a default argument to the given non-type template
287/// parameter.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000288void Sema::ActOnNonTypeTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000289 SourceLocation EqualLoc,
290 ExprArg DefaultE) {
291 NonTypeTemplateParmDecl *TemplateParm
Chris Lattner5261d0c2009-03-28 19:18:32 +0000292 = cast<NonTypeTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregor9225a7e2009-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 Gregored3a3982009-03-03 04:44:36 +0000300 if (CheckTemplateArgument(TemplateParm, TemplateParm->getType(), Default)) {
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000301 TemplateParm->setInvalidDecl();
302 return;
303 }
304
Anders Carlsson39ecdcf2009-05-01 19:49:17 +0000305 TemplateParm->setDefaultArgument(DefaultE.takeAs<Expr>());
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000306}
307
Douglas Gregor279272e2009-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 Lattner5261d0c2009-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 Gregor279272e2009-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 Lattner5261d0c2009-03-28 19:18:32 +0000341 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor279272e2009-02-04 19:02:06 +0000342 IdResolver.AddDecl(Param);
343 }
344
Chris Lattner5261d0c2009-03-28 19:18:32 +0000345 return DeclPtrTy::make(Param);
Douglas Gregor279272e2009-02-04 19:02:06 +0000346}
347
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000348/// \brief Adds a default argument to the given template template
349/// parameter.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000350void Sema::ActOnTemplateTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000351 SourceLocation EqualLoc,
352 ExprArg DefaultE) {
353 TemplateTemplateParmDecl *TemplateParm
Chris Lattner5261d0c2009-03-28 19:18:32 +0000354 = cast<TemplateTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregor9225a7e2009-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 Gregor52473432008-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 Lattner5261d0c2009-03-28 19:18:32 +0000389 DeclPtrTy *Params, unsigned NumParams,
Douglas Gregor52473432008-12-24 02:52:09 +0000390 SourceLocation RAngleLoc) {
391 if (ExportLoc.isValid())
392 Diag(ExportLoc, diag::note_template_export_unsupported);
393
Douglas Gregord406b032009-02-06 22:42:48 +0000394 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
395 (Decl**)Params, NumParams, RAngleLoc);
Douglas Gregor52473432008-12-24 02:52:09 +0000396}
Douglas Gregor279272e2009-02-04 19:02:06 +0000397
Douglas Gregorc5d6fa72009-03-25 00:13:59 +0000398Sema::DeclResult
Douglas Gregord406b032009-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 Carlssoned20fb92009-03-26 00:52:18 +0000403 MultiTemplateParamsArg TemplateParameterLists,
404 AccessSpecifier AS) {
Douglas Gregord406b032009-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 Gregor9225a7e2009-02-10 19:49:53 +0000407 bool Invalid = false;
Douglas Gregord406b032009-02-06 22:42:48 +0000408
409 // Check that we can declare a template here.
410 if (CheckTemplateDeclScope(S, TemplateParameterLists))
Douglas Gregorc5d6fa72009-03-25 00:13:59 +0000411 return true;
Douglas Gregord406b032009-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 Gregorc5d6fa72009-03-25 00:13:59 +0000424 return true;
Douglas Gregord406b032009-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 Gregor734b4ba2009-03-19 00:18:19 +0000437 SemanticContext = computeDeclContext(SS);
Douglas Gregord406b032009-02-06 22:42:48 +0000438
439 // FIXME: need to match up several levels of template parameter
440 // lists here.
441 }
442
443 // FIXME: member templates!
444 TemplateParameterList *TemplateParams
445 = static_cast<TemplateParameterList *>(*TemplateParameterLists.release());
446
447 // If there is a previous declaration with the same name, check
448 // whether this is a valid redeclaration.
449 ClassTemplateDecl *PrevClassTemplate
450 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
451 if (PrevClassTemplate) {
452 // Ensure that the template parameter lists are compatible.
453 if (!TemplateParameterListsAreEqual(TemplateParams,
454 PrevClassTemplate->getTemplateParameters(),
455 /*Complain=*/true))
Douglas Gregorc5d6fa72009-03-25 00:13:59 +0000456 return true;
Douglas Gregord406b032009-02-06 22:42:48 +0000457
458 // C++ [temp.class]p4:
459 // In a redeclaration, partial specialization, explicit
460 // specialization or explicit instantiation of a class template,
461 // the class-key shall agree in kind with the original class
462 // template declaration (7.1.5.3).
463 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Douglas Gregor625185c2009-05-14 16:41:31 +0000464 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind, KWLoc, *Name)) {
Douglas Gregor3faaa812009-04-01 23:51:29 +0000465 Diag(KWLoc, diag::err_use_with_wrong_tag)
466 << Name
467 << CodeModificationHint::CreateReplacement(KWLoc,
468 PrevRecordDecl->getKindName());
Douglas Gregord406b032009-02-06 22:42:48 +0000469 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregor3faaa812009-04-01 23:51:29 +0000470 Kind = PrevRecordDecl->getTagKind();
Douglas Gregord406b032009-02-06 22:42:48 +0000471 }
472
Douglas Gregord406b032009-02-06 22:42:48 +0000473 // Check for redefinition of this class template.
474 if (TK == TK_Definition) {
475 if (TagDecl *Def = PrevRecordDecl->getDefinition(Context)) {
476 Diag(NameLoc, diag::err_redefinition) << Name;
477 Diag(Def->getLocation(), diag::note_previous_definition);
478 // FIXME: Would it make sense to try to "forget" the previous
479 // definition, as part of error recovery?
Douglas Gregorc5d6fa72009-03-25 00:13:59 +0000480 return true;
Douglas Gregord406b032009-02-06 22:42:48 +0000481 }
482 }
483 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
484 // Maybe we will complain about the shadowed template parameter.
485 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
486 // Just pretend that we didn't see the previous declaration.
487 PrevDecl = 0;
488 } else if (PrevDecl) {
489 // C++ [temp]p5:
490 // A class template shall not have the same name as any other
491 // template, class, function, object, enumeration, enumerator,
492 // namespace, or type in the same scope (3.3), except as specified
493 // in (14.5.4).
494 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
495 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregorc5d6fa72009-03-25 00:13:59 +0000496 return true;
Douglas Gregord406b032009-02-06 22:42:48 +0000497 }
498
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000499 // Check the template parameter list of this declaration, possibly
500 // merging in the template parameter list from the previous class
501 // template declaration.
502 if (CheckTemplateParameterList(TemplateParams,
503 PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0))
504 Invalid = true;
505
Douglas Gregor9054f982009-05-10 22:57:19 +0000506 // FIXME: If we had a scope specifier, we better have a previous template
Douglas Gregord406b032009-02-06 22:42:48 +0000507 // declaration!
508
Douglas Gregor55216ac2009-03-26 00:10:35 +0000509 CXXRecordDecl *NewClass =
Douglas Gregord406b032009-02-06 22:42:48 +0000510 CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name,
511 PrevClassTemplate?
Douglas Gregor12aed0b2009-05-15 19:11:46 +0000512 PrevClassTemplate->getTemplatedDecl() : 0,
513 /*DelayTypeCreation=*/true);
Douglas Gregord406b032009-02-06 22:42:48 +0000514
515 ClassTemplateDecl *NewTemplate
516 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
517 DeclarationName(Name), TemplateParams,
Douglas Gregor47bde7c2009-03-19 17:26:29 +0000518 NewClass, PrevClassTemplate);
Douglas Gregor55216ac2009-03-26 00:10:35 +0000519 NewClass->setDescribedClassTemplate(NewTemplate);
520
Douglas Gregor12aed0b2009-05-15 19:11:46 +0000521 // Build the type for the class template declaration now.
522 QualType T =
523 Context.getTypeDeclType(NewClass,
524 PrevClassTemplate?
525 PrevClassTemplate->getTemplatedDecl() : 0);
526 assert(T->isDependentType() && "Class template type is not dependent?");
527 (void)T;
528
Anders Carlsson4ca43492009-03-26 01:24:28 +0000529 // Set the access specifier.
530 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
531
Douglas Gregord406b032009-02-06 22:42:48 +0000532 // Set the lexical context of these templates
533 NewClass->setLexicalDeclContext(CurContext);
534 NewTemplate->setLexicalDeclContext(CurContext);
535
536 if (TK == TK_Definition)
537 NewClass->startDefinition();
538
539 if (Attr)
540 ProcessDeclAttributeList(NewClass, Attr);
541
542 PushOnScopeChains(NewTemplate, S);
543
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000544 if (Invalid) {
545 NewTemplate->setInvalidDecl();
546 NewClass->setInvalidDecl();
547 }
Chris Lattner5261d0c2009-03-28 19:18:32 +0000548 return DeclPtrTy::make(NewTemplate);
Douglas Gregord406b032009-02-06 22:42:48 +0000549}
550
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000551/// \brief Checks the validity of a template parameter list, possibly
552/// considering the template parameter list from a previous
553/// declaration.
554///
555/// If an "old" template parameter list is provided, it must be
556/// equivalent (per TemplateParameterListsAreEqual) to the "new"
557/// template parameter list.
558///
559/// \param NewParams Template parameter list for a new template
560/// declaration. This template parameter list will be updated with any
561/// default arguments that are carried through from the previous
562/// template parameter list.
563///
564/// \param OldParams If provided, template parameter list from a
565/// previous declaration of the same template. Default template
566/// arguments will be merged from the old template parameter list to
567/// the new template parameter list.
568///
569/// \returns true if an error occurred, false otherwise.
570bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
571 TemplateParameterList *OldParams) {
572 bool Invalid = false;
573
574 // C++ [temp.param]p10:
575 // The set of default template-arguments available for use with a
576 // template declaration or definition is obtained by merging the
577 // default arguments from the definition (if in scope) and all
578 // declarations in scope in the same way default function
579 // arguments are (8.3.6).
580 bool SawDefaultArgument = false;
581 SourceLocation PreviousDefaultArgLoc;
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000582
Mike Stumpe0b7e032009-02-11 23:03:27 +0000583 // Dummy initialization to avoid warnings.
Douglas Gregorc5363f42009-02-11 20:46:19 +0000584 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000585 if (OldParams)
586 OldParam = OldParams->begin();
587
588 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
589 NewParamEnd = NewParams->end();
590 NewParam != NewParamEnd; ++NewParam) {
591 // Variables used to diagnose redundant default arguments
592 bool RedundantDefaultArg = false;
593 SourceLocation OldDefaultLoc;
594 SourceLocation NewDefaultLoc;
595
596 // Variables used to diagnose missing default arguments
597 bool MissingDefaultArg = false;
598
599 // Merge default arguments for template type parameters.
600 if (TemplateTypeParmDecl *NewTypeParm
601 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
602 TemplateTypeParmDecl *OldTypeParm
603 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
604
605 if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
606 NewTypeParm->hasDefaultArgument()) {
607 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
608 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
609 SawDefaultArgument = true;
610 RedundantDefaultArg = true;
611 PreviousDefaultArgLoc = NewDefaultLoc;
612 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
613 // Merge the default argument from the old declaration to the
614 // new declaration.
615 SawDefaultArgument = true;
616 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgument(),
617 OldTypeParm->getDefaultArgumentLoc(),
618 true);
619 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
620 } else if (NewTypeParm->hasDefaultArgument()) {
621 SawDefaultArgument = true;
622 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
623 } else if (SawDefaultArgument)
624 MissingDefaultArg = true;
625 }
626 // Merge default arguments for non-type template parameters
627 else if (NonTypeTemplateParmDecl *NewNonTypeParm
628 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
629 NonTypeTemplateParmDecl *OldNonTypeParm
630 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
631 if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
632 NewNonTypeParm->hasDefaultArgument()) {
633 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
634 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
635 SawDefaultArgument = true;
636 RedundantDefaultArg = true;
637 PreviousDefaultArgLoc = NewDefaultLoc;
638 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
639 // Merge the default argument from the old declaration to the
640 // new declaration.
641 SawDefaultArgument = true;
642 // FIXME: We need to create a new kind of "default argument"
643 // expression that points to a previous template template
644 // parameter.
645 NewNonTypeParm->setDefaultArgument(
646 OldNonTypeParm->getDefaultArgument());
647 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
648 } else if (NewNonTypeParm->hasDefaultArgument()) {
649 SawDefaultArgument = true;
650 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
651 } else if (SawDefaultArgument)
652 MissingDefaultArg = true;
653 }
654 // Merge default arguments for template template parameters
655 else {
656 TemplateTemplateParmDecl *NewTemplateParm
657 = cast<TemplateTemplateParmDecl>(*NewParam);
658 TemplateTemplateParmDecl *OldTemplateParm
659 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
660 if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
661 NewTemplateParm->hasDefaultArgument()) {
662 OldDefaultLoc = OldTemplateParm->getDefaultArgumentLoc();
663 NewDefaultLoc = NewTemplateParm->getDefaultArgumentLoc();
664 SawDefaultArgument = true;
665 RedundantDefaultArg = true;
666 PreviousDefaultArgLoc = NewDefaultLoc;
667 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
668 // Merge the default argument from the old declaration to the
669 // new declaration.
670 SawDefaultArgument = true;
671 // FIXME: We need to create a new kind of "default argument"
672 // expression that points to a previous template template
673 // parameter.
674 NewTemplateParm->setDefaultArgument(
675 OldTemplateParm->getDefaultArgument());
676 PreviousDefaultArgLoc = OldTemplateParm->getDefaultArgumentLoc();
677 } else if (NewTemplateParm->hasDefaultArgument()) {
678 SawDefaultArgument = true;
679 PreviousDefaultArgLoc = NewTemplateParm->getDefaultArgumentLoc();
680 } else if (SawDefaultArgument)
681 MissingDefaultArg = true;
682 }
683
684 if (RedundantDefaultArg) {
685 // C++ [temp.param]p12:
686 // A template-parameter shall not be given default arguments
687 // by two different declarations in the same scope.
688 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
689 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
690 Invalid = true;
691 } else if (MissingDefaultArg) {
692 // C++ [temp.param]p11:
693 // If a template-parameter has a default template-argument,
694 // all subsequent template-parameters shall have a default
695 // template-argument supplied.
696 Diag((*NewParam)->getLocation(),
697 diag::err_template_param_default_arg_missing);
698 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
699 Invalid = true;
700 }
701
702 // If we have an old template parameter list that we're merging
703 // in, move on to the next parameter.
704 if (OldParams)
705 ++OldParam;
706 }
707
708 return Invalid;
709}
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000710
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000711/// \brief Translates template arguments as provided by the parser
712/// into template arguments used by semantic analysis.
713static void
714translateTemplateArguments(ASTTemplateArgsPtr &TemplateArgsIn,
715 SourceLocation *TemplateArgLocs,
716 llvm::SmallVector<TemplateArgument, 16> &TemplateArgs) {
717 TemplateArgs.reserve(TemplateArgsIn.size());
718
719 void **Args = TemplateArgsIn.getArgs();
720 bool *ArgIsType = TemplateArgsIn.getArgIsType();
721 for (unsigned Arg = 0, Last = TemplateArgsIn.size(); Arg != Last; ++Arg) {
722 TemplateArgs.push_back(
723 ArgIsType[Arg]? TemplateArgument(TemplateArgLocs[Arg],
724 QualType::getFromOpaquePtr(Args[Arg]))
725 : TemplateArgument(reinterpret_cast<Expr *>(Args[Arg])));
726 }
727}
728
Douglas Gregoraabb8502009-03-31 00:43:58 +0000729/// \brief Build a canonical version of a template argument list.
730///
731/// This function builds a canonical version of the given template
732/// argument list, where each of the template arguments has been
733/// converted into its canonical form. This routine is typically used
734/// to canonicalize a template argument list when the template name
735/// itself is dependent. When the template name refers to an actual
736/// template declaration, Sema::CheckTemplateArgumentList should be
737/// used to check and canonicalize the template arguments.
738///
739/// \param TemplateArgs The incoming template arguments.
740///
741/// \param NumTemplateArgs The number of template arguments in \p
742/// TemplateArgs.
743///
744/// \param Canonical A vector to be filled with the canonical versions
745/// of the template arguments.
746///
747/// \param Context The ASTContext in which the template arguments live.
748static void CanonicalizeTemplateArguments(const TemplateArgument *TemplateArgs,
749 unsigned NumTemplateArgs,
750 llvm::SmallVectorImpl<TemplateArgument> &Canonical,
751 ASTContext &Context) {
752 Canonical.reserve(NumTemplateArgs);
753 for (unsigned Idx = 0; Idx < NumTemplateArgs; ++Idx) {
754 switch (TemplateArgs[Idx].getKind()) {
755 case TemplateArgument::Expression:
756 // FIXME: Build canonical expression (!)
757 Canonical.push_back(TemplateArgs[Idx]);
758 break;
759
760 case TemplateArgument::Declaration:
Douglas Gregor9054f982009-05-10 22:57:19 +0000761 Canonical.push_back(
762 TemplateArgument(SourceLocation(),
763 Context.getCanonicalDecl(TemplateArgs[Idx].getAsDecl())));
Douglas Gregoraabb8502009-03-31 00:43:58 +0000764 break;
765
766 case TemplateArgument::Integral:
767 Canonical.push_back(TemplateArgument(SourceLocation(),
768 *TemplateArgs[Idx].getAsIntegral(),
769 TemplateArgs[Idx].getIntegralType()));
770
771 case TemplateArgument::Type: {
772 QualType CanonType
773 = Context.getCanonicalType(TemplateArgs[Idx].getAsType());
774 Canonical.push_back(TemplateArgument(SourceLocation(), CanonType));
775 }
776 }
777 }
778}
779
Douglas Gregordd13e842009-03-30 22:58:21 +0000780QualType Sema::CheckTemplateIdType(TemplateName Name,
781 SourceLocation TemplateLoc,
782 SourceLocation LAngleLoc,
783 const TemplateArgument *TemplateArgs,
784 unsigned NumTemplateArgs,
785 SourceLocation RAngleLoc) {
786 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregoraabb8502009-03-31 00:43:58 +0000787 if (!Template) {
788 // The template name does not resolve to a template, so we just
789 // build a dependent template-id type.
790
791 // Canonicalize the template arguments to build the canonical
792 // template-id type.
793 llvm::SmallVector<TemplateArgument, 16> CanonicalTemplateArgs;
794 CanonicalizeTemplateArguments(TemplateArgs, NumTemplateArgs,
795 CanonicalTemplateArgs, Context);
796
Douglas Gregor905406b2009-05-07 06:49:52 +0000797 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
Douglas Gregoraabb8502009-03-31 00:43:58 +0000798 QualType CanonType
Douglas Gregor905406b2009-05-07 06:49:52 +0000799 = Context.getTemplateSpecializationType(CanonName,
800 &CanonicalTemplateArgs[0],
Douglas Gregoraabb8502009-03-31 00:43:58 +0000801 CanonicalTemplateArgs.size());
802
803 // Build the dependent template-id type.
804 return Context.getTemplateSpecializationType(Name, TemplateArgs,
805 NumTemplateArgs, CanonType);
806 }
Douglas Gregordd13e842009-03-30 22:58:21 +0000807
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000808 // Check that the template argument list is well-formed for this
809 // template.
810 llvm::SmallVector<TemplateArgument, 16> ConvertedTemplateArgs;
Douglas Gregordd13e842009-03-30 22:58:21 +0000811 if (CheckTemplateArgumentList(Template, TemplateLoc, LAngleLoc,
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000812 TemplateArgs, NumTemplateArgs, RAngleLoc,
813 ConvertedTemplateArgs))
814 return QualType();
815
816 assert((ConvertedTemplateArgs.size() ==
Douglas Gregordd13e842009-03-30 22:58:21 +0000817 Template->getTemplateParameters()->size()) &&
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000818 "Converted template argument list is too short!");
819
820 QualType CanonType;
821
Douglas Gregordd13e842009-03-30 22:58:21 +0000822 if (TemplateSpecializationType::anyDependentTemplateArguments(
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000823 TemplateArgs,
824 NumTemplateArgs)) {
825 // This class template specialization is a dependent
826 // type. Therefore, its canonical type is another class template
827 // specialization type that contains all of the converted
828 // arguments in canonical form. This ensures that, e.g., A<T> and
829 // A<T, T> have identical types when A is declared as:
830 //
831 // template<typename T, typename U = T> struct A;
Douglas Gregorb88ba412009-05-07 06:41:52 +0000832 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
833 CanonType = Context.getTemplateSpecializationType(CanonName,
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000834 &ConvertedTemplateArgs[0],
835 ConvertedTemplateArgs.size());
Douglas Gregordd13e842009-03-30 22:58:21 +0000836 } else if (ClassTemplateDecl *ClassTemplate
837 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000838 // Find the class template specialization declaration that
839 // corresponds to these arguments.
840 llvm::FoldingSetNodeID ID;
841 ClassTemplateSpecializationDecl::Profile(ID, &ConvertedTemplateArgs[0],
842 ConvertedTemplateArgs.size());
843 void *InsertPos = 0;
844 ClassTemplateSpecializationDecl *Decl
845 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
846 if (!Decl) {
847 // This is the first time we have referenced this class template
848 // specialization. Create the canonical declaration and add it to
849 // the set of specializations.
850 Decl = ClassTemplateSpecializationDecl::Create(Context,
851 ClassTemplate->getDeclContext(),
852 TemplateLoc,
853 ClassTemplate,
854 &ConvertedTemplateArgs[0],
855 ConvertedTemplateArgs.size(),
856 0);
857 ClassTemplate->getSpecializations().InsertNode(Decl, InsertPos);
858 Decl->setLexicalDeclContext(CurContext);
859 }
860
861 CanonType = Context.getTypeDeclType(Decl);
862 }
863
864 // Build the fully-sugared type for this class template
865 // specialization, which refers back to the class template
866 // specialization we created or found.
Douglas Gregordd13e842009-03-30 22:58:21 +0000867 return Context.getTemplateSpecializationType(Name, TemplateArgs,
868 NumTemplateArgs, CanonType);
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000869}
870
Douglas Gregora08b6c72009-02-17 23:15:12 +0000871Action::TypeResult
Douglas Gregordd13e842009-03-30 22:58:21 +0000872Sema::ActOnTemplateIdType(TemplateTy TemplateD, SourceLocation TemplateLoc,
873 SourceLocation LAngleLoc,
874 ASTTemplateArgsPtr TemplateArgsIn,
875 SourceLocation *TemplateArgLocs,
876 SourceLocation RAngleLoc) {
877 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Douglas Gregor8e458f42009-02-09 18:46:07 +0000878
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000879 // Translate the parser's template argument list in our AST format.
880 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
881 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000882
Douglas Gregordd13e842009-03-30 22:58:21 +0000883 QualType Result = CheckTemplateIdType(Template, TemplateLoc, LAngleLoc,
884 &TemplateArgs[0], TemplateArgs.size(),
885 RAngleLoc);
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000886 TemplateArgsIn.release();
Douglas Gregord7cb0372009-04-01 21:51:26 +0000887
888 if (Result.isNull())
889 return true;
890
Douglas Gregor6f37b582009-02-09 19:34:22 +0000891 return Result.getAsOpaquePtr();
Douglas Gregor8e458f42009-02-09 18:46:07 +0000892}
893
Douglas Gregoraabb8502009-03-31 00:43:58 +0000894/// \brief Form a dependent template name.
895///
896/// This action forms a dependent template name given the template
897/// name and its (presumably dependent) scope specifier. For
898/// example, given "MetaFun::template apply", the scope specifier \p
899/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
900/// of the "template" keyword, and "apply" is the \p Name.
901Sema::TemplateTy
902Sema::ActOnDependentTemplateName(SourceLocation TemplateKWLoc,
903 const IdentifierInfo &Name,
904 SourceLocation NameLoc,
905 const CXXScopeSpec &SS) {
906 if (!SS.isSet() || SS.isInvalid())
907 return TemplateTy();
908
909 NestedNameSpecifier *Qualifier
910 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
911
912 // FIXME: member of the current instantiation
913
914 if (!Qualifier->isDependent()) {
915 // C++0x [temp.names]p5:
916 // If a name prefixed by the keyword template is not the name of
917 // a template, the program is ill-formed. [Note: the keyword
918 // template may not be applied to non-template members of class
919 // templates. -end note ] [ Note: as is the case with the
920 // typename prefix, the template prefix is allowed in cases
921 // where it is not strictly necessary; i.e., when the
922 // nested-name-specifier or the expression on the left of the ->
923 // or . is not dependent on a template-parameter, or the use
924 // does not appear in the scope of a template. -end note]
925 //
926 // Note: C++03 was more strict here, because it banned the use of
927 // the "template" keyword prior to a template-name that was not a
928 // dependent name. C++ DR468 relaxed this requirement (the
929 // "template" keyword is now permitted). We follow the C++0x
930 // rules, even in C++03 mode, retroactively applying the DR.
931 TemplateTy Template;
932 TemplateNameKind TNK = isTemplateName(Name, 0, Template, &SS);
933 if (TNK == TNK_Non_template) {
934 Diag(NameLoc, diag::err_template_kw_refers_to_non_template)
935 << &Name;
936 return TemplateTy();
937 }
938
939 return Template;
940 }
941
942 return TemplateTy::make(Context.getDependentTemplateName(Qualifier, &Name));
943}
944
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000945/// \brief Check that the given template argument list is well-formed
946/// for specializing the given template.
947bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
948 SourceLocation TemplateLoc,
949 SourceLocation LAngleLoc,
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000950 const TemplateArgument *TemplateArgs,
951 unsigned NumTemplateArgs,
Douglas Gregorad964b32009-02-17 01:05:43 +0000952 SourceLocation RAngleLoc,
953 llvm::SmallVectorImpl<TemplateArgument> &Converted) {
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000954 TemplateParameterList *Params = Template->getTemplateParameters();
955 unsigned NumParams = Params->size();
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000956 unsigned NumArgs = NumTemplateArgs;
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000957 bool Invalid = false;
958
959 if (NumArgs > NumParams ||
Douglas Gregorc347d8e2009-02-11 18:16:40 +0000960 NumArgs < Params->getMinRequiredArguments()) {
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000961 // FIXME: point at either the first arg beyond what we can handle,
962 // or the '>', depending on whether we have too many or too few
963 // arguments.
964 SourceRange Range;
965 if (NumArgs > NumParams)
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000966 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000967 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
968 << (NumArgs > NumParams)
969 << (isa<ClassTemplateDecl>(Template)? 0 :
970 isa<FunctionTemplateDecl>(Template)? 1 :
971 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
972 << Template << Range;
Douglas Gregorc347d8e2009-02-11 18:16:40 +0000973 Diag(Template->getLocation(), diag::note_template_decl_here)
974 << Params->getSourceRange();
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000975 Invalid = true;
976 }
977
978 // C++ [temp.arg]p1:
979 // [...] The type and form of each template-argument specified in
980 // a template-id shall match the type and form specified for the
981 // corresponding parameter declared by the template in its
982 // template-parameter-list.
983 unsigned ArgIdx = 0;
984 for (TemplateParameterList::iterator Param = Params->begin(),
985 ParamEnd = Params->end();
986 Param != ParamEnd; ++Param, ++ArgIdx) {
987 // Decode the template argument
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000988 TemplateArgument Arg;
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000989 if (ArgIdx >= NumArgs) {
Douglas Gregorad964b32009-02-17 01:05:43 +0000990 // Retrieve the default template argument from the template
991 // parameter.
992 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
993 if (!TTP->hasDefaultArgument())
994 break;
995
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000996 QualType ArgType = TTP->getDefaultArgument();
Douglas Gregor74296542009-02-27 19:31:52 +0000997
998 // If the argument type is dependent, instantiate it now based
999 // on the previously-computed template arguments.
Douglas Gregor56d25a72009-03-10 20:44:00 +00001000 if (ArgType->isDependentType()) {
1001 InstantiatingTemplate Inst(*this, TemplateLoc,
1002 Template, &Converted[0],
1003 Converted.size(),
1004 SourceRange(TemplateLoc, RAngleLoc));
Douglas Gregorf9e7d3d2009-05-11 23:53:27 +00001005
1006 TemplateArgumentList TemplateArgs(Context, &Converted[0],
1007 Converted.size(),
1008 /*CopyArgs=*/false);
1009 ArgType = InstantiateType(ArgType, TemplateArgs,
Douglas Gregor74296542009-02-27 19:31:52 +00001010 TTP->getDefaultArgumentLoc(),
1011 TTP->getDeclName());
Douglas Gregor56d25a72009-03-10 20:44:00 +00001012 }
Douglas Gregor74296542009-02-27 19:31:52 +00001013
1014 if (ArgType.isNull())
Douglas Gregorf57dcd02009-02-28 00:25:32 +00001015 return true;
Douglas Gregor74296542009-02-27 19:31:52 +00001016
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001017 Arg = TemplateArgument(TTP->getLocation(), ArgType);
Douglas Gregorad964b32009-02-17 01:05:43 +00001018 } else if (NonTypeTemplateParmDecl *NTTP
1019 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
1020 if (!NTTP->hasDefaultArgument())
1021 break;
1022
Douglas Gregored3a3982009-03-03 04:44:36 +00001023 // FIXME: Instantiate default argument
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001024 Arg = TemplateArgument(NTTP->getDefaultArgument());
Douglas Gregorad964b32009-02-17 01:05:43 +00001025 } else {
1026 TemplateTemplateParmDecl *TempParm
1027 = cast<TemplateTemplateParmDecl>(*Param);
1028
1029 if (!TempParm->hasDefaultArgument())
1030 break;
1031
Douglas Gregored3a3982009-03-03 04:44:36 +00001032 // FIXME: Instantiate default argument
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001033 Arg = TemplateArgument(TempParm->getDefaultArgument());
Douglas Gregorad964b32009-02-17 01:05:43 +00001034 }
1035 } else {
1036 // Retrieve the template argument produced by the user.
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001037 Arg = TemplateArgs[ArgIdx];
Douglas Gregorad964b32009-02-17 01:05:43 +00001038 }
1039
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001040
1041 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
1042 // Check template type parameters.
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001043 if (Arg.getKind() == TemplateArgument::Type) {
1044 if (CheckTemplateArgument(TTP, Arg.getAsType(), Arg.getLocation()))
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001045 Invalid = true;
Douglas Gregorad964b32009-02-17 01:05:43 +00001046
1047 // Add the converted template type argument.
1048 Converted.push_back(
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001049 TemplateArgument(Arg.getLocation(),
1050 Context.getCanonicalType(Arg.getAsType())));
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001051 continue;
1052 }
1053
1054 // C++ [temp.arg.type]p1:
1055 // A template-argument for a template-parameter which is a
1056 // type shall be a type-id.
1057
1058 // We have a template type parameter but the template argument
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001059 // is not a type.
1060 Diag(Arg.getLocation(), diag::err_template_arg_must_be_type);
Douglas Gregor341ac792009-02-10 00:53:15 +00001061 Diag((*Param)->getLocation(), diag::note_template_param_here);
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001062 Invalid = true;
1063 } else if (NonTypeTemplateParmDecl *NTTP
1064 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
1065 // Check non-type template parameters.
Douglas Gregored3a3982009-03-03 04:44:36 +00001066
1067 // Instantiate the type of the non-type template parameter with
1068 // the template arguments we've seen thus far.
1069 QualType NTTPType = NTTP->getType();
1070 if (NTTPType->isDependentType()) {
1071 // Instantiate the type of the non-type template parameter.
Douglas Gregor56d25a72009-03-10 20:44:00 +00001072 InstantiatingTemplate Inst(*this, TemplateLoc,
1073 Template, &Converted[0],
1074 Converted.size(),
1075 SourceRange(TemplateLoc, RAngleLoc));
1076
Douglas Gregorf9e7d3d2009-05-11 23:53:27 +00001077 TemplateArgumentList TemplateArgs(Context, &Converted[0],
1078 Converted.size(),
1079 /*CopyArgs=*/false);
1080 NTTPType = InstantiateType(NTTPType, TemplateArgs,
Douglas Gregored3a3982009-03-03 04:44:36 +00001081 NTTP->getLocation(),
1082 NTTP->getDeclName());
1083 // If that worked, check the non-type template parameter type
1084 // for validity.
1085 if (!NTTPType.isNull())
1086 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
1087 NTTP->getLocation());
1088
1089 if (NTTPType.isNull()) {
1090 Invalid = true;
1091 break;
1092 }
1093 }
1094
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001095 switch (Arg.getKind()) {
1096 case TemplateArgument::Expression: {
1097 Expr *E = Arg.getAsExpr();
1098 if (CheckTemplateArgument(NTTP, NTTPType, E, &Converted))
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001099 Invalid = true;
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001100 break;
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001101 }
1102
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001103 case TemplateArgument::Declaration:
1104 case TemplateArgument::Integral:
1105 // We've already checked this template argument, so just copy
1106 // it to the list of converted arguments.
1107 Converted.push_back(Arg);
1108 break;
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001109
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001110 case TemplateArgument::Type:
1111 // We have a non-type template parameter but the template
1112 // argument is a type.
1113
1114 // C++ [temp.arg]p2:
1115 // In a template-argument, an ambiguity between a type-id and
1116 // an expression is resolved to a type-id, regardless of the
1117 // form of the corresponding template-parameter.
1118 //
1119 // We warn specifically about this case, since it can be rather
1120 // confusing for users.
1121 if (Arg.getAsType()->isFunctionType())
1122 Diag(Arg.getLocation(), diag::err_template_arg_nontype_ambig)
1123 << Arg.getAsType();
1124 else
1125 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr);
1126 Diag((*Param)->getLocation(), diag::note_template_param_here);
1127 Invalid = true;
1128 }
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001129 } else {
1130 // Check template template parameters.
1131 TemplateTemplateParmDecl *TempParm
1132 = cast<TemplateTemplateParmDecl>(*Param);
1133
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001134 switch (Arg.getKind()) {
1135 case TemplateArgument::Expression: {
1136 Expr *ArgExpr = Arg.getAsExpr();
1137 if (ArgExpr && isa<DeclRefExpr>(ArgExpr) &&
1138 isa<TemplateDecl>(cast<DeclRefExpr>(ArgExpr)->getDecl())) {
1139 if (CheckTemplateArgument(TempParm, cast<DeclRefExpr>(ArgExpr)))
1140 Invalid = true;
1141
1142 // Add the converted template argument.
Douglas Gregor9054f982009-05-10 22:57:19 +00001143 Decl *D
1144 = Context.getCanonicalDecl(cast<DeclRefExpr>(ArgExpr)->getDecl());
1145 Converted.push_back(TemplateArgument(Arg.getLocation(), D));
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001146 continue;
1147 }
1148 }
1149 // fall through
1150
1151 case TemplateArgument::Type: {
1152 // We have a template template parameter but the template
1153 // argument does not refer to a template.
1154 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
1155 Invalid = true;
1156 break;
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001157 }
1158
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001159 case TemplateArgument::Declaration:
1160 // We've already checked this template argument, so just copy
1161 // it to the list of converted arguments.
1162 Converted.push_back(Arg);
1163 break;
1164
1165 case TemplateArgument::Integral:
1166 assert(false && "Integral argument with template template parameter");
1167 break;
1168 }
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001169 }
1170 }
1171
1172 return Invalid;
1173}
1174
1175/// \brief Check a template argument against its corresponding
1176/// template type parameter.
1177///
1178/// This routine implements the semantics of C++ [temp.arg.type]. It
1179/// returns true if an error occurred, and false otherwise.
1180bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
1181 QualType Arg, SourceLocation ArgLoc) {
1182 // C++ [temp.arg.type]p2:
1183 // A local type, a type with no linkage, an unnamed type or a type
1184 // compounded from any of these types shall not be used as a
1185 // template-argument for a template type-parameter.
1186 //
1187 // FIXME: Perform the recursive and no-linkage type checks.
1188 const TagType *Tag = 0;
1189 if (const EnumType *EnumT = Arg->getAsEnumType())
1190 Tag = EnumT;
1191 else if (const RecordType *RecordT = Arg->getAsRecordType())
1192 Tag = RecordT;
1193 if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod())
1194 return Diag(ArgLoc, diag::err_template_arg_local_type)
1195 << QualType(Tag, 0);
Douglas Gregor04385782009-03-10 18:33:27 +00001196 else if (Tag && !Tag->getDecl()->getDeclName() &&
1197 !Tag->getDecl()->getTypedefForAnonDecl()) {
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001198 Diag(ArgLoc, diag::err_template_arg_unnamed_type);
1199 Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here);
1200 return true;
1201 }
1202
1203 return false;
1204}
1205
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001206/// \brief Checks whether the given template argument is the address
1207/// of an object or function according to C++ [temp.arg.nontype]p1.
Douglas Gregorad964b32009-02-17 01:05:43 +00001208bool Sema::CheckTemplateArgumentAddressOfObjectOrFunction(Expr *Arg,
1209 NamedDecl *&Entity) {
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001210 bool Invalid = false;
1211
1212 // See through any implicit casts we added to fix the type.
1213 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
1214 Arg = Cast->getSubExpr();
1215
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001216 // C++0x allows nullptr, and there's no further checking to be done for that.
1217 if (Arg->getType()->isNullPtrType())
1218 return false;
1219
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001220 // C++ [temp.arg.nontype]p1:
1221 //
1222 // A template-argument for a non-type, non-template
1223 // template-parameter shall be one of: [...]
1224 //
1225 // -- the address of an object or function with external
1226 // linkage, including function templates and function
1227 // template-ids but excluding non-static class members,
1228 // expressed as & id-expression where the & is optional if
1229 // the name refers to a function or array, or if the
1230 // corresponding template-parameter is a reference; or
1231 DeclRefExpr *DRE = 0;
1232
1233 // Ignore (and complain about) any excess parentheses.
1234 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
1235 if (!Invalid) {
1236 Diag(Arg->getSourceRange().getBegin(),
1237 diag::err_template_arg_extra_parens)
1238 << Arg->getSourceRange();
1239 Invalid = true;
1240 }
1241
1242 Arg = Parens->getSubExpr();
1243 }
1244
1245 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
1246 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
1247 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
1248 } else
1249 DRE = dyn_cast<DeclRefExpr>(Arg);
1250
1251 if (!DRE || !isa<ValueDecl>(DRE->getDecl()))
1252 return Diag(Arg->getSourceRange().getBegin(),
1253 diag::err_template_arg_not_object_or_func_form)
1254 << Arg->getSourceRange();
1255
1256 // Cannot refer to non-static data members
1257 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl()))
1258 return Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
1259 << Field << Arg->getSourceRange();
1260
1261 // Cannot refer to non-static member functions
1262 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
1263 if (!Method->isStatic())
1264 return Diag(Arg->getSourceRange().getBegin(),
1265 diag::err_template_arg_method)
1266 << Method << Arg->getSourceRange();
1267
1268 // Functions must have external linkage.
1269 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
1270 if (Func->getStorageClass() == FunctionDecl::Static) {
1271 Diag(Arg->getSourceRange().getBegin(),
1272 diag::err_template_arg_function_not_extern)
1273 << Func << Arg->getSourceRange();
1274 Diag(Func->getLocation(), diag::note_template_arg_internal_object)
1275 << true;
1276 return true;
1277 }
1278
1279 // Okay: we've named a function with external linkage.
Douglas Gregorad964b32009-02-17 01:05:43 +00001280 Entity = Func;
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001281 return Invalid;
1282 }
1283
1284 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
1285 if (!Var->hasGlobalStorage()) {
1286 Diag(Arg->getSourceRange().getBegin(),
1287 diag::err_template_arg_object_not_extern)
1288 << Var << Arg->getSourceRange();
1289 Diag(Var->getLocation(), diag::note_template_arg_internal_object)
1290 << true;
1291 return true;
1292 }
1293
1294 // Okay: we've named an object with external linkage
Douglas Gregorad964b32009-02-17 01:05:43 +00001295 Entity = Var;
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001296 return Invalid;
1297 }
1298
1299 // We found something else, but we don't know specifically what it is.
1300 Diag(Arg->getSourceRange().getBegin(),
1301 diag::err_template_arg_not_object_or_func)
1302 << Arg->getSourceRange();
1303 Diag(DRE->getDecl()->getLocation(),
1304 diag::note_template_arg_refers_here);
1305 return true;
1306}
1307
1308/// \brief Checks whether the given template argument is a pointer to
1309/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregorad964b32009-02-17 01:05:43 +00001310bool
1311Sema::CheckTemplateArgumentPointerToMember(Expr *Arg, NamedDecl *&Member) {
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001312 bool Invalid = false;
1313
1314 // See through any implicit casts we added to fix the type.
1315 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
1316 Arg = Cast->getSubExpr();
1317
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001318 // C++0x allows nullptr, and there's no further checking to be done for that.
1319 if (Arg->getType()->isNullPtrType())
1320 return false;
1321
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001322 // C++ [temp.arg.nontype]p1:
1323 //
1324 // A template-argument for a non-type, non-template
1325 // template-parameter shall be one of: [...]
1326 //
1327 // -- a pointer to member expressed as described in 5.3.1.
1328 QualifiedDeclRefExpr *DRE = 0;
1329
1330 // Ignore (and complain about) any excess parentheses.
1331 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
1332 if (!Invalid) {
1333 Diag(Arg->getSourceRange().getBegin(),
1334 diag::err_template_arg_extra_parens)
1335 << Arg->getSourceRange();
1336 Invalid = true;
1337 }
1338
1339 Arg = Parens->getSubExpr();
1340 }
1341
1342 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg))
1343 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
1344 DRE = dyn_cast<QualifiedDeclRefExpr>(UnOp->getSubExpr());
1345
1346 if (!DRE)
1347 return Diag(Arg->getSourceRange().getBegin(),
1348 diag::err_template_arg_not_pointer_to_member_form)
1349 << Arg->getSourceRange();
1350
1351 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
1352 assert((isa<FieldDecl>(DRE->getDecl()) ||
1353 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
1354 "Only non-static member pointers can make it here");
1355
1356 // Okay: this is the address of a non-static member, and therefore
1357 // a member pointer constant.
Douglas Gregorad964b32009-02-17 01:05:43 +00001358 Member = DRE->getDecl();
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001359 return Invalid;
1360 }
1361
1362 // We found something else, but we don't know specifically what it is.
1363 Diag(Arg->getSourceRange().getBegin(),
1364 diag::err_template_arg_not_pointer_to_member_form)
1365 << Arg->getSourceRange();
1366 Diag(DRE->getDecl()->getLocation(),
1367 diag::note_template_arg_refers_here);
1368 return true;
1369}
1370
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001371/// \brief Check a template argument against its corresponding
1372/// non-type template parameter.
1373///
Douglas Gregored3a3982009-03-03 04:44:36 +00001374/// This routine implements the semantics of C++ [temp.arg.nontype].
1375/// It returns true if an error occurred, and false otherwise. \p
1376/// InstantiatedParamType is the type of the non-type template
1377/// parameter after it has been instantiated.
Douglas Gregorad964b32009-02-17 01:05:43 +00001378///
1379/// If Converted is non-NULL and no errors occur, the value
1380/// of this argument will be added to the end of the Converted vector.
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001381bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Douglas Gregored3a3982009-03-03 04:44:36 +00001382 QualType InstantiatedParamType, Expr *&Arg,
Douglas Gregorad964b32009-02-17 01:05:43 +00001383 llvm::SmallVectorImpl<TemplateArgument> *Converted) {
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001384 SourceLocation StartLoc = Arg->getSourceRange().getBegin();
1385
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001386 // If either the parameter has a dependent type or the argument is
1387 // type-dependent, there's nothing we can check now.
Douglas Gregorad964b32009-02-17 01:05:43 +00001388 // FIXME: Add template argument to Converted!
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001389 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
1390 // FIXME: Produce a cloned, canonical expression?
1391 Converted->push_back(TemplateArgument(Arg));
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001392 return false;
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001393 }
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001394
1395 // C++ [temp.arg.nontype]p5:
1396 // The following conversions are performed on each expression used
1397 // as a non-type template-argument. If a non-type
1398 // template-argument cannot be converted to the type of the
1399 // corresponding template-parameter then the program is
1400 // ill-formed.
1401 //
1402 // -- for a non-type template-parameter of integral or
1403 // enumeration type, integral promotions (4.5) and integral
1404 // conversions (4.7) are applied.
Douglas Gregored3a3982009-03-03 04:44:36 +00001405 QualType ParamType = InstantiatedParamType;
Douglas Gregor2eedd992009-02-11 00:19:33 +00001406 QualType ArgType = Arg->getType();
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001407 if (ParamType->isIntegralType() || ParamType->isEnumeralType()) {
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001408 // C++ [temp.arg.nontype]p1:
1409 // A template-argument for a non-type, non-template
1410 // template-parameter shall be one of:
1411 //
1412 // -- an integral constant-expression of integral or enumeration
1413 // type; or
1414 // -- the name of a non-type template-parameter; or
1415 SourceLocation NonConstantLoc;
Douglas Gregorad964b32009-02-17 01:05:43 +00001416 llvm::APSInt Value;
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001417 if (!ArgType->isIntegralType() && !ArgType->isEnumeralType()) {
1418 Diag(Arg->getSourceRange().getBegin(),
1419 diag::err_template_arg_not_integral_or_enumeral)
1420 << ArgType << Arg->getSourceRange();
1421 Diag(Param->getLocation(), diag::note_template_param_here);
1422 return true;
1423 } else if (!Arg->isValueDependent() &&
Douglas Gregorad964b32009-02-17 01:05:43 +00001424 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001425 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
1426 << ArgType << Arg->getSourceRange();
1427 return true;
1428 }
1429
1430 // FIXME: We need some way to more easily get the unqualified form
1431 // of the types without going all the way to the
1432 // canonical type.
1433 if (Context.getCanonicalType(ParamType).getCVRQualifiers())
1434 ParamType = Context.getCanonicalType(ParamType).getUnqualifiedType();
1435 if (Context.getCanonicalType(ArgType).getCVRQualifiers())
1436 ArgType = Context.getCanonicalType(ArgType).getUnqualifiedType();
1437
1438 // Try to convert the argument to the parameter's type.
1439 if (ParamType == ArgType) {
1440 // Okay: no conversion necessary
1441 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
1442 !ParamType->isEnumeralType()) {
1443 // This is an integral promotion or conversion.
1444 ImpCastExprToType(Arg, ParamType);
1445 } else {
1446 // We can't perform this conversion.
1447 Diag(Arg->getSourceRange().getBegin(),
1448 diag::err_template_arg_not_convertible)
Douglas Gregored3a3982009-03-03 04:44:36 +00001449 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001450 Diag(Param->getLocation(), diag::note_template_param_here);
1451 return true;
1452 }
1453
Douglas Gregorafc86942009-03-14 00:20:21 +00001454 QualType IntegerType = Context.getCanonicalType(ParamType);
1455 if (const EnumType *Enum = IntegerType->getAsEnumType())
1456 IntegerType = Enum->getDecl()->getIntegerType();
1457
1458 if (!Arg->isValueDependent()) {
1459 // Check that an unsigned parameter does not receive a negative
1460 // value.
1461 if (IntegerType->isUnsignedIntegerType()
1462 && (Value.isSigned() && Value.isNegative())) {
1463 Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_negative)
1464 << Value.toString(10) << Param->getType()
1465 << Arg->getSourceRange();
1466 Diag(Param->getLocation(), diag::note_template_param_here);
1467 return true;
1468 }
1469
1470 // Check that we don't overflow the template parameter type.
1471 unsigned AllowedBits = Context.getTypeSize(IntegerType);
1472 if (Value.getActiveBits() > AllowedBits) {
1473 Diag(Arg->getSourceRange().getBegin(),
1474 diag::err_template_arg_too_large)
1475 << Value.toString(10) << Param->getType()
1476 << Arg->getSourceRange();
1477 Diag(Param->getLocation(), diag::note_template_param_here);
1478 return true;
1479 }
1480
1481 if (Value.getBitWidth() != AllowedBits)
1482 Value.extOrTrunc(AllowedBits);
1483 Value.setIsSigned(IntegerType->isSignedIntegerType());
1484 }
Douglas Gregorad964b32009-02-17 01:05:43 +00001485
1486 if (Converted) {
1487 // Add the value of this argument to the list of converted
1488 // arguments. We use the bitwidth and signedness of the template
1489 // parameter.
Douglas Gregor396f1142009-03-13 21:01:28 +00001490 if (Arg->isValueDependent()) {
1491 // The argument is value-dependent. Create a new
1492 // TemplateArgument with the converted expression.
1493 Converted->push_back(TemplateArgument(Arg));
1494 return false;
1495 }
1496
Douglas Gregor544cda62009-03-14 00:03:48 +00001497 Converted->push_back(TemplateArgument(StartLoc, Value,
Douglas Gregor63f5d602009-03-12 22:20:26 +00001498 Context.getCanonicalType(IntegerType)));
Douglas Gregorad964b32009-02-17 01:05:43 +00001499 }
1500
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001501 return false;
1502 }
Douglas Gregor2eedd992009-02-11 00:19:33 +00001503
Douglas Gregor3f411962009-02-11 01:18:59 +00001504 // Handle pointer-to-function, reference-to-function, and
1505 // pointer-to-member-function all in (roughly) the same way.
1506 if (// -- For a non-type template-parameter of type pointer to
1507 // function, only the function-to-pointer conversion (4.3) is
1508 // applied. If the template-argument represents a set of
1509 // overloaded functions (or a pointer to such), the matching
1510 // function is selected from the set (13.4).
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001511 // In C++0x, any std::nullptr_t value can be converted.
Douglas Gregor3f411962009-02-11 01:18:59 +00001512 (ParamType->isPointerType() &&
1513 ParamType->getAsPointerType()->getPointeeType()->isFunctionType()) ||
1514 // -- For a non-type template-parameter of type reference to
1515 // function, no conversions apply. If the template-argument
1516 // represents a set of overloaded functions, the matching
1517 // function is selected from the set (13.4).
1518 (ParamType->isReferenceType() &&
1519 ParamType->getAsReferenceType()->getPointeeType()->isFunctionType()) ||
1520 // -- For a non-type template-parameter of type pointer to
1521 // member function, no conversions apply. If the
1522 // template-argument represents a set of overloaded member
1523 // functions, the matching member function is selected from
1524 // the set (13.4).
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001525 // Again, C++0x allows a std::nullptr_t value.
Douglas Gregor3f411962009-02-11 01:18:59 +00001526 (ParamType->isMemberPointerType() &&
1527 ParamType->getAsMemberPointerType()->getPointeeType()
1528 ->isFunctionType())) {
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001529 if (Context.hasSameUnqualifiedType(ArgType,
1530 ParamType.getNonReferenceType())) {
Douglas Gregor2eedd992009-02-11 00:19:33 +00001531 // We don't have to do anything: the types already match.
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001532 } else if (ArgType->isNullPtrType() && (ParamType->isPointerType() ||
1533 ParamType->isMemberPointerType())) {
1534 ArgType = ParamType;
1535 ImpCastExprToType(Arg, ParamType);
Douglas Gregor3f411962009-02-11 01:18:59 +00001536 } else if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregor2eedd992009-02-11 00:19:33 +00001537 ArgType = Context.getPointerType(ArgType);
1538 ImpCastExprToType(Arg, ArgType);
1539 } else if (FunctionDecl *Fn
1540 = ResolveAddressOfOverloadedFunction(Arg, ParamType, true)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00001541 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
1542 return true;
1543
Douglas Gregor2eedd992009-02-11 00:19:33 +00001544 FixOverloadedFunctionReference(Arg, Fn);
1545 ArgType = Arg->getType();
Douglas Gregor3f411962009-02-11 01:18:59 +00001546 if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregor2eedd992009-02-11 00:19:33 +00001547 ArgType = Context.getPointerType(Arg->getType());
1548 ImpCastExprToType(Arg, ArgType);
1549 }
1550 }
1551
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001552 if (!Context.hasSameUnqualifiedType(ArgType,
1553 ParamType.getNonReferenceType())) {
Douglas Gregor2eedd992009-02-11 00:19:33 +00001554 // We can't perform this conversion.
1555 Diag(Arg->getSourceRange().getBegin(),
1556 diag::err_template_arg_not_convertible)
Douglas Gregored3a3982009-03-03 04:44:36 +00001557 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor2eedd992009-02-11 00:19:33 +00001558 Diag(Param->getLocation(), diag::note_template_param_here);
1559 return true;
1560 }
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001561
Douglas Gregorad964b32009-02-17 01:05:43 +00001562 if (ParamType->isMemberPointerType()) {
1563 NamedDecl *Member = 0;
1564 if (CheckTemplateArgumentPointerToMember(Arg, Member))
1565 return true;
1566
Douglas Gregor9054f982009-05-10 22:57:19 +00001567 if (Converted) {
Douglas Gregor8a7f1fa2009-05-10 23:27:08 +00001568 Member = cast_or_null<NamedDecl>(Context.getCanonicalDecl(Member));
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001569 Converted->push_back(TemplateArgument(StartLoc, Member));
Douglas Gregor9054f982009-05-10 22:57:19 +00001570 }
Douglas Gregorad964b32009-02-17 01:05:43 +00001571
1572 return false;
1573 }
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001574
Douglas Gregorad964b32009-02-17 01:05:43 +00001575 NamedDecl *Entity = 0;
1576 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1577 return true;
1578
Douglas Gregor9054f982009-05-10 22:57:19 +00001579 if (Converted) {
Douglas Gregor8a7f1fa2009-05-10 23:27:08 +00001580 Entity = cast_or_null<NamedDecl>(Context.getCanonicalDecl(Entity));
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001581 Converted->push_back(TemplateArgument(StartLoc, Entity));
Douglas Gregor9054f982009-05-10 22:57:19 +00001582 }
Douglas Gregorad964b32009-02-17 01:05:43 +00001583 return false;
Douglas Gregor2eedd992009-02-11 00:19:33 +00001584 }
1585
Chris Lattner320dff22009-02-20 21:37:53 +00001586 if (ParamType->isPointerType()) {
Douglas Gregor3f411962009-02-11 01:18:59 +00001587 // -- for a non-type template-parameter of type pointer to
1588 // object, qualification conversions (4.4) and the
1589 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001590 // C++0x also allows a value of std::nullptr_t.
Douglas Gregor26ea1222009-03-24 20:32:41 +00001591 assert(ParamType->getAsPointerType()->getPointeeType()->isObjectType() &&
Douglas Gregor3f411962009-02-11 01:18:59 +00001592 "Only object pointers allowed here");
Douglas Gregord8c8c092009-02-11 00:44:29 +00001593
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001594 if (ArgType->isNullPtrType()) {
1595 ArgType = ParamType;
1596 ImpCastExprToType(Arg, ParamType);
1597 } else if (ArgType->isArrayType()) {
Douglas Gregor3f411962009-02-11 01:18:59 +00001598 ArgType = Context.getArrayDecayedType(ArgType);
1599 ImpCastExprToType(Arg, ArgType);
Douglas Gregord8c8c092009-02-11 00:44:29 +00001600 }
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001601
Douglas Gregor3f411962009-02-11 01:18:59 +00001602 if (IsQualificationConversion(ArgType, ParamType)) {
1603 ArgType = ParamType;
1604 ImpCastExprToType(Arg, ParamType);
1605 }
1606
Douglas Gregor0ea4e302009-02-11 18:22:40 +00001607 if (!Context.hasSameUnqualifiedType(ArgType, ParamType)) {
Douglas Gregor3f411962009-02-11 01:18:59 +00001608 // We can't perform this conversion.
1609 Diag(Arg->getSourceRange().getBegin(),
1610 diag::err_template_arg_not_convertible)
Douglas Gregored3a3982009-03-03 04:44:36 +00001611 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor3f411962009-02-11 01:18:59 +00001612 Diag(Param->getLocation(), diag::note_template_param_here);
1613 return true;
1614 }
1615
Douglas Gregorad964b32009-02-17 01:05:43 +00001616 NamedDecl *Entity = 0;
1617 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1618 return true;
1619
Douglas Gregor9054f982009-05-10 22:57:19 +00001620 if (Converted) {
Douglas Gregor8a7f1fa2009-05-10 23:27:08 +00001621 Entity = cast_or_null<NamedDecl>(Context.getCanonicalDecl(Entity));
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001622 Converted->push_back(TemplateArgument(StartLoc, Entity));
Douglas Gregor9054f982009-05-10 22:57:19 +00001623 }
Douglas Gregorad964b32009-02-17 01:05:43 +00001624
1625 return false;
Douglas Gregord8c8c092009-02-11 00:44:29 +00001626 }
Douglas Gregor3f411962009-02-11 01:18:59 +00001627
1628 if (const ReferenceType *ParamRefType = ParamType->getAsReferenceType()) {
1629 // -- For a non-type template-parameter of type reference to
1630 // object, no conversions apply. The type referred to by the
1631 // reference may be more cv-qualified than the (otherwise
1632 // identical) type of the template-argument. The
1633 // template-parameter is bound directly to the
1634 // template-argument, which must be an lvalue.
Douglas Gregor26ea1222009-03-24 20:32:41 +00001635 assert(ParamRefType->getPointeeType()->isObjectType() &&
Douglas Gregor3f411962009-02-11 01:18:59 +00001636 "Only object references allowed here");
Douglas Gregord8c8c092009-02-11 00:44:29 +00001637
Douglas Gregor0ea4e302009-02-11 18:22:40 +00001638 if (!Context.hasSameUnqualifiedType(ParamRefType->getPointeeType(), ArgType)) {
Douglas Gregor3f411962009-02-11 01:18:59 +00001639 Diag(Arg->getSourceRange().getBegin(),
1640 diag::err_template_arg_no_ref_bind)
Douglas Gregored3a3982009-03-03 04:44:36 +00001641 << InstantiatedParamType << Arg->getType()
Douglas Gregor3f411962009-02-11 01:18:59 +00001642 << Arg->getSourceRange();
1643 Diag(Param->getLocation(), diag::note_template_param_here);
1644 return true;
1645 }
1646
1647 unsigned ParamQuals
1648 = Context.getCanonicalType(ParamType).getCVRQualifiers();
1649 unsigned ArgQuals = Context.getCanonicalType(ArgType).getCVRQualifiers();
1650
1651 if ((ParamQuals | ArgQuals) != ParamQuals) {
1652 Diag(Arg->getSourceRange().getBegin(),
1653 diag::err_template_arg_ref_bind_ignores_quals)
Douglas Gregored3a3982009-03-03 04:44:36 +00001654 << InstantiatedParamType << Arg->getType()
Douglas Gregor3f411962009-02-11 01:18:59 +00001655 << Arg->getSourceRange();
1656 Diag(Param->getLocation(), diag::note_template_param_here);
1657 return true;
1658 }
1659
Douglas Gregorad964b32009-02-17 01:05:43 +00001660 NamedDecl *Entity = 0;
1661 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1662 return true;
1663
Douglas Gregor9054f982009-05-10 22:57:19 +00001664 if (Converted) {
1665 Entity = cast<NamedDecl>(Context.getCanonicalDecl(Entity));
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001666 Converted->push_back(TemplateArgument(StartLoc, Entity));
Douglas Gregor9054f982009-05-10 22:57:19 +00001667 }
Douglas Gregorad964b32009-02-17 01:05:43 +00001668
1669 return false;
Douglas Gregor3f411962009-02-11 01:18:59 +00001670 }
Douglas Gregor3628e1b2009-02-11 16:16:59 +00001671
1672 // -- For a non-type template-parameter of type pointer to data
1673 // member, qualification conversions (4.4) are applied.
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001674 // C++0x allows std::nullptr_t values.
Douglas Gregor3628e1b2009-02-11 16:16:59 +00001675 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
1676
Douglas Gregor0ea4e302009-02-11 18:22:40 +00001677 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
Douglas Gregor3628e1b2009-02-11 16:16:59 +00001678 // Types match exactly: nothing more to do here.
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001679 } else if (ArgType->isNullPtrType()) {
1680 ImpCastExprToType(Arg, ParamType);
Douglas Gregor3628e1b2009-02-11 16:16:59 +00001681 } else if (IsQualificationConversion(ArgType, ParamType)) {
1682 ImpCastExprToType(Arg, ParamType);
1683 } else {
1684 // We can't perform this conversion.
1685 Diag(Arg->getSourceRange().getBegin(),
1686 diag::err_template_arg_not_convertible)
Douglas Gregored3a3982009-03-03 04:44:36 +00001687 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor3628e1b2009-02-11 16:16:59 +00001688 Diag(Param->getLocation(), diag::note_template_param_here);
1689 return true;
1690 }
1691
Douglas Gregorad964b32009-02-17 01:05:43 +00001692 NamedDecl *Member = 0;
1693 if (CheckTemplateArgumentPointerToMember(Arg, Member))
1694 return true;
1695
Douglas Gregor9054f982009-05-10 22:57:19 +00001696 if (Converted) {
Douglas Gregor8a7f1fa2009-05-10 23:27:08 +00001697 Member = cast_or_null<NamedDecl>(Context.getCanonicalDecl(Member));
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001698 Converted->push_back(TemplateArgument(StartLoc, Member));
Douglas Gregor9054f982009-05-10 22:57:19 +00001699 }
1700
Douglas Gregorad964b32009-02-17 01:05:43 +00001701 return false;
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001702}
1703
1704/// \brief Check a template argument against its corresponding
1705/// template template parameter.
1706///
1707/// This routine implements the semantics of C++ [temp.arg.template].
1708/// It returns true if an error occurred, and false otherwise.
1709bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
1710 DeclRefExpr *Arg) {
Douglas Gregore8e367f2009-02-10 00:24:35 +00001711 assert(isa<TemplateDecl>(Arg->getDecl()) && "Only template decls allowed");
1712 TemplateDecl *Template = cast<TemplateDecl>(Arg->getDecl());
1713
1714 // C++ [temp.arg.template]p1:
1715 // A template-argument for a template template-parameter shall be
1716 // the name of a class template, expressed as id-expression. Only
1717 // primary class templates are considered when matching the
1718 // template template argument with the corresponding parameter;
1719 // partial specializations are not considered even if their
1720 // parameter lists match that of the template template parameter.
1721 if (!isa<ClassTemplateDecl>(Template)) {
1722 assert(isa<FunctionTemplateDecl>(Template) &&
1723 "Only function templates are possible here");
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001724 Diag(Arg->getSourceRange().getBegin(),
1725 diag::note_template_arg_refers_here_func)
Douglas Gregore8e367f2009-02-10 00:24:35 +00001726 << Template;
1727 }
1728
1729 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
1730 Param->getTemplateParameters(),
1731 true, true,
1732 Arg->getSourceRange().getBegin());
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001733}
1734
Douglas Gregord406b032009-02-06 22:42:48 +00001735/// \brief Determine whether the given template parameter lists are
1736/// equivalent.
1737///
1738/// \param New The new template parameter list, typically written in the
1739/// source code as part of a new template declaration.
1740///
1741/// \param Old The old template parameter list, typically found via
1742/// name lookup of the template declared with this template parameter
1743/// list.
1744///
1745/// \param Complain If true, this routine will produce a diagnostic if
1746/// the template parameter lists are not equivalent.
1747///
Douglas Gregore8e367f2009-02-10 00:24:35 +00001748/// \param IsTemplateTemplateParm If true, this routine is being
1749/// called to compare the template parameter lists of a template
1750/// template parameter.
1751///
1752/// \param TemplateArgLoc If this source location is valid, then we
1753/// are actually checking the template parameter list of a template
1754/// argument (New) against the template parameter list of its
1755/// corresponding template template parameter (Old). We produce
1756/// slightly different diagnostics in this scenario.
1757///
Douglas Gregord406b032009-02-06 22:42:48 +00001758/// \returns True if the template parameter lists are equal, false
1759/// otherwise.
1760bool
1761Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
1762 TemplateParameterList *Old,
1763 bool Complain,
Douglas Gregore8e367f2009-02-10 00:24:35 +00001764 bool IsTemplateTemplateParm,
1765 SourceLocation TemplateArgLoc) {
Douglas Gregord406b032009-02-06 22:42:48 +00001766 if (Old->size() != New->size()) {
1767 if (Complain) {
Douglas Gregore8e367f2009-02-10 00:24:35 +00001768 unsigned NextDiag = diag::err_template_param_list_different_arity;
1769 if (TemplateArgLoc.isValid()) {
1770 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
1771 NextDiag = diag::note_template_param_list_different_arity;
1772 }
1773 Diag(New->getTemplateLoc(), NextDiag)
1774 << (New->size() > Old->size())
1775 << IsTemplateTemplateParm
1776 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
Douglas Gregord406b032009-02-06 22:42:48 +00001777 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
1778 << IsTemplateTemplateParm
1779 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
1780 }
1781
1782 return false;
1783 }
1784
1785 for (TemplateParameterList::iterator OldParm = Old->begin(),
1786 OldParmEnd = Old->end(), NewParm = New->begin();
1787 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
1788 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
Douglas Gregore8e367f2009-02-10 00:24:35 +00001789 unsigned NextDiag = diag::err_template_param_different_kind;
1790 if (TemplateArgLoc.isValid()) {
1791 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
1792 NextDiag = diag::note_template_param_different_kind;
1793 }
1794 Diag((*NewParm)->getLocation(), NextDiag)
Douglas Gregord406b032009-02-06 22:42:48 +00001795 << IsTemplateTemplateParm;
1796 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
1797 << IsTemplateTemplateParm;
1798 return false;
1799 }
1800
1801 if (isa<TemplateTypeParmDecl>(*OldParm)) {
1802 // Okay; all template type parameters are equivalent (since we
Douglas Gregore8e367f2009-02-10 00:24:35 +00001803 // know we're at the same index).
1804#if 0
1805 // FIXME: Enable this code in debug mode *after* we properly go
1806 // through and "instantiate" the template parameter lists of
1807 // template template parameters. It's only after this
1808 // instantiation that (1) any dependent types within the
1809 // template parameter list of the template template parameter
1810 // can be checked, and (2) the template type parameter depths
1811 // will match up.
Douglas Gregord406b032009-02-06 22:42:48 +00001812 QualType OldParmType
1813 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*OldParm));
1814 QualType NewParmType
1815 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*NewParm));
1816 assert(Context.getCanonicalType(OldParmType) ==
1817 Context.getCanonicalType(NewParmType) &&
1818 "type parameter mismatch?");
1819#endif
1820 } else if (NonTypeTemplateParmDecl *OldNTTP
1821 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
1822 // The types of non-type template parameters must agree.
1823 NonTypeTemplateParmDecl *NewNTTP
1824 = cast<NonTypeTemplateParmDecl>(*NewParm);
1825 if (Context.getCanonicalType(OldNTTP->getType()) !=
1826 Context.getCanonicalType(NewNTTP->getType())) {
1827 if (Complain) {
Douglas Gregore8e367f2009-02-10 00:24:35 +00001828 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
1829 if (TemplateArgLoc.isValid()) {
1830 Diag(TemplateArgLoc,
1831 diag::err_template_arg_template_params_mismatch);
1832 NextDiag = diag::note_template_nontype_parm_different_type;
1833 }
1834 Diag(NewNTTP->getLocation(), NextDiag)
Douglas Gregord406b032009-02-06 22:42:48 +00001835 << NewNTTP->getType()
1836 << IsTemplateTemplateParm;
1837 Diag(OldNTTP->getLocation(),
1838 diag::note_template_nontype_parm_prev_declaration)
1839 << OldNTTP->getType();
1840 }
1841 return false;
1842 }
1843 } else {
1844 // The template parameter lists of template template
1845 // parameters must agree.
1846 // FIXME: Could we perform a faster "type" comparison here?
1847 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
1848 "Only template template parameters handled here");
1849 TemplateTemplateParmDecl *OldTTP
1850 = cast<TemplateTemplateParmDecl>(*OldParm);
1851 TemplateTemplateParmDecl *NewTTP
1852 = cast<TemplateTemplateParmDecl>(*NewParm);
1853 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
1854 OldTTP->getTemplateParameters(),
1855 Complain,
Douglas Gregore8e367f2009-02-10 00:24:35 +00001856 /*IsTemplateTemplateParm=*/true,
1857 TemplateArgLoc))
Douglas Gregord406b032009-02-06 22:42:48 +00001858 return false;
1859 }
1860 }
1861
1862 return true;
1863}
1864
1865/// \brief Check whether a template can be declared within this scope.
1866///
1867/// If the template declaration is valid in this scope, returns
1868/// false. Otherwise, issues a diagnostic and returns true.
1869bool
1870Sema::CheckTemplateDeclScope(Scope *S,
1871 MultiTemplateParamsArg &TemplateParameterLists) {
1872 assert(TemplateParameterLists.size() > 0 && "Not a template");
1873
1874 // Find the nearest enclosing declaration scope.
1875 while ((S->getFlags() & Scope::DeclScope) == 0 ||
1876 (S->getFlags() & Scope::TemplateParamScope) != 0)
1877 S = S->getParent();
1878
1879 TemplateParameterList *TemplateParams =
1880 static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
1881 SourceLocation TemplateLoc = TemplateParams->getTemplateLoc();
1882 SourceRange TemplateRange
1883 = SourceRange(TemplateLoc, TemplateParams->getRAngleLoc());
1884
1885 // C++ [temp]p2:
1886 // A template-declaration can appear only as a namespace scope or
1887 // class scope declaration.
1888 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
1889 while (Ctx && isa<LinkageSpecDecl>(Ctx)) {
1890 if (cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
1891 return Diag(TemplateLoc, diag::err_template_linkage)
1892 << TemplateRange;
1893
1894 Ctx = Ctx->getParent();
1895 }
1896
1897 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
1898 return false;
1899
1900 return Diag(TemplateLoc, diag::err_template_outside_namespace_or_class_scope)
1901 << TemplateRange;
1902}
Douglas Gregora08b6c72009-02-17 23:15:12 +00001903
Douglas Gregor90177912009-05-13 18:28:20 +00001904/// \brief Check whether a class template specialization or explicit
1905/// instantiation in the current context is well-formed.
Douglas Gregor0d93f692009-02-25 22:02:03 +00001906///
Douglas Gregor90177912009-05-13 18:28:20 +00001907/// This routine determines whether a class template specialization or
1908/// explicit instantiation can be declared in the current context
1909/// (C++ [temp.expl.spec]p2, C++0x [temp.explicit]p2) and emits
1910/// appropriate diagnostics if there was an error. It returns true if
1911// there was an error that we cannot recover from, and false otherwise.
Douglas Gregor0d93f692009-02-25 22:02:03 +00001912bool
1913Sema::CheckClassTemplateSpecializationScope(ClassTemplateDecl *ClassTemplate,
1914 ClassTemplateSpecializationDecl *PrevDecl,
1915 SourceLocation TemplateNameLoc,
Douglas Gregor90177912009-05-13 18:28:20 +00001916 SourceRange ScopeSpecifierRange,
1917 bool ExplicitInstantiation) {
Douglas Gregor0d93f692009-02-25 22:02:03 +00001918 // C++ [temp.expl.spec]p2:
1919 // An explicit specialization shall be declared in the namespace
1920 // of which the template is a member, or, for member templates, in
1921 // the namespace of which the enclosing class or enclosing class
1922 // template is a member. An explicit specialization of a member
1923 // function, member class or static data member of a class
1924 // template shall be declared in the namespace of which the class
1925 // template is a member. Such a declaration may also be a
1926 // definition. If the declaration is not a definition, the
1927 // specialization may be defined later in the name- space in which
1928 // the explicit specialization was declared, or in a namespace
1929 // that encloses the one in which the explicit specialization was
1930 // declared.
1931 if (CurContext->getLookupContext()->isFunctionOrMethod()) {
1932 Diag(TemplateNameLoc, diag::err_template_spec_decl_function_scope)
Douglas Gregor90177912009-05-13 18:28:20 +00001933 << ExplicitInstantiation << ClassTemplate;
Douglas Gregor0d93f692009-02-25 22:02:03 +00001934 return true;
1935 }
1936
1937 DeclContext *DC = CurContext->getEnclosingNamespaceContext();
1938 DeclContext *TemplateContext
1939 = ClassTemplate->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregor90177912009-05-13 18:28:20 +00001940 if ((!PrevDecl || PrevDecl->getSpecializationKind() == TSK_Undeclared) &&
1941 !ExplicitInstantiation) {
Douglas Gregor0d93f692009-02-25 22:02:03 +00001942 // There is no prior declaration of this entity, so this
1943 // specialization must be in the same context as the template
1944 // itself.
1945 if (DC != TemplateContext) {
1946 if (isa<TranslationUnitDecl>(TemplateContext))
1947 Diag(TemplateNameLoc, diag::err_template_spec_decl_out_of_scope_global)
1948 << ClassTemplate << ScopeSpecifierRange;
1949 else if (isa<NamespaceDecl>(TemplateContext))
1950 Diag(TemplateNameLoc, diag::err_template_spec_decl_out_of_scope)
1951 << ClassTemplate << cast<NamedDecl>(TemplateContext)
1952 << ScopeSpecifierRange;
1953
1954 Diag(ClassTemplate->getLocation(), diag::note_template_decl_here);
1955 }
1956
1957 return false;
1958 }
1959
1960 // We have a previous declaration of this entity. Make sure that
1961 // this redeclaration (or definition) occurs in an enclosing namespace.
1962 if (!CurContext->Encloses(TemplateContext)) {
Douglas Gregor90177912009-05-13 18:28:20 +00001963 // FIXME: In C++98, we would like to turn these errors into
1964 // warnings, dependent on a -Wc++0x flag.
1965 bool SuppressedDiag = false;
1966 if (isa<TranslationUnitDecl>(TemplateContext)) {
1967 if (!ExplicitInstantiation || getLangOptions().CPlusPlus0x)
1968 Diag(TemplateNameLoc, diag::err_template_spec_redecl_global_scope)
1969 << ExplicitInstantiation << ClassTemplate << ScopeSpecifierRange;
1970 else
1971 SuppressedDiag = true;
1972 } else if (isa<NamespaceDecl>(TemplateContext)) {
1973 if (!ExplicitInstantiation || getLangOptions().CPlusPlus0x)
1974 Diag(TemplateNameLoc, diag::err_template_spec_redecl_out_of_scope)
1975 << ExplicitInstantiation << ClassTemplate
1976 << cast<NamedDecl>(TemplateContext) << ScopeSpecifierRange;
1977 else
1978 SuppressedDiag = true;
1979 }
Douglas Gregor0d93f692009-02-25 22:02:03 +00001980
Douglas Gregor90177912009-05-13 18:28:20 +00001981 if (!SuppressedDiag)
1982 Diag(ClassTemplate->getLocation(), diag::note_template_decl_here);
Douglas Gregor0d93f692009-02-25 22:02:03 +00001983 }
1984
1985 return false;
1986}
1987
Douglas Gregorc5d6fa72009-03-25 00:13:59 +00001988Sema::DeclResult
Douglas Gregora08b6c72009-02-17 23:15:12 +00001989Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec, TagKind TK,
1990 SourceLocation KWLoc,
1991 const CXXScopeSpec &SS,
Douglas Gregordd13e842009-03-30 22:58:21 +00001992 TemplateTy TemplateD,
Douglas Gregora08b6c72009-02-17 23:15:12 +00001993 SourceLocation TemplateNameLoc,
1994 SourceLocation LAngleLoc,
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001995 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregora08b6c72009-02-17 23:15:12 +00001996 SourceLocation *TemplateArgLocs,
1997 SourceLocation RAngleLoc,
1998 AttributeList *Attr,
1999 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregora08b6c72009-02-17 23:15:12 +00002000 // Find the class template we're specializing
Douglas Gregordd13e842009-03-30 22:58:21 +00002001 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Douglas Gregora08b6c72009-02-17 23:15:12 +00002002 ClassTemplateDecl *ClassTemplate
Douglas Gregordd13e842009-03-30 22:58:21 +00002003 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
Douglas Gregora08b6c72009-02-17 23:15:12 +00002004
Douglas Gregor0d93f692009-02-25 22:02:03 +00002005 // Check the validity of the template headers that introduce this
2006 // template.
Douglas Gregor50113ca2009-02-25 22:18:32 +00002007 // FIXME: Once we have member templates, we'll need to check
2008 // C++ [temp.expl.spec]p17-18, where we could have multiple levels of
2009 // template<> headers.
Douglas Gregor3bb30002009-02-26 21:00:50 +00002010 if (TemplateParameterLists.size() == 0)
2011 Diag(KWLoc, diag::err_template_spec_needs_header)
Douglas Gregor61be3602009-02-27 17:53:17 +00002012 << CodeModificationHint::CreateInsertion(KWLoc, "template<> ");
Douglas Gregor3bb30002009-02-26 21:00:50 +00002013 else {
Douglas Gregor0d93f692009-02-25 22:02:03 +00002014 TemplateParameterList *TemplateParams
2015 = static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
Chris Lattner5261d0c2009-03-28 19:18:32 +00002016 if (TemplateParameterLists.size() > 1) {
2017 Diag(TemplateParams->getTemplateLoc(),
2018 diag::err_template_spec_extra_headers);
2019 return true;
2020 }
Douglas Gregor0d93f692009-02-25 22:02:03 +00002021
Chris Lattner5261d0c2009-03-28 19:18:32 +00002022 if (TemplateParams->size() > 0) {
Douglas Gregor0d93f692009-02-25 22:02:03 +00002023 // FIXME: No support for class template partial specialization.
Chris Lattner5261d0c2009-03-28 19:18:32 +00002024 Diag(TemplateParams->getTemplateLoc(), diag::unsup_template_partial_spec);
2025 return true;
2026 }
Douglas Gregor0d93f692009-02-25 22:02:03 +00002027 }
2028
Douglas Gregora08b6c72009-02-17 23:15:12 +00002029 // Check that the specialization uses the same tag kind as the
2030 // original template.
2031 TagDecl::TagKind Kind;
2032 switch (TagSpec) {
2033 default: assert(0 && "Unknown tag type!");
2034 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2035 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2036 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2037 }
Douglas Gregor625185c2009-05-14 16:41:31 +00002038 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
2039 Kind, KWLoc,
2040 *ClassTemplate->getIdentifier())) {
Douglas Gregor3faaa812009-04-01 23:51:29 +00002041 Diag(KWLoc, diag::err_use_with_wrong_tag)
2042 << ClassTemplate
2043 << CodeModificationHint::CreateReplacement(KWLoc,
2044 ClassTemplate->getTemplatedDecl()->getKindName());
Douglas Gregora08b6c72009-02-17 23:15:12 +00002045 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
2046 diag::note_previous_use);
2047 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
2048 }
2049
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00002050 // Translate the parser's template argument list in our AST format.
2051 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
2052 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
2053
Douglas Gregora08b6c72009-02-17 23:15:12 +00002054 // Check that the template argument list is well-formed for this
2055 // template.
2056 llvm::SmallVector<TemplateArgument, 16> ConvertedTemplateArgs;
2057 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00002058 &TemplateArgs[0], TemplateArgs.size(),
2059 RAngleLoc, ConvertedTemplateArgs))
Douglas Gregorc5d6fa72009-03-25 00:13:59 +00002060 return true;
Douglas Gregora08b6c72009-02-17 23:15:12 +00002061
2062 assert((ConvertedTemplateArgs.size() ==
2063 ClassTemplate->getTemplateParameters()->size()) &&
2064 "Converted template argument list is too short!");
2065
2066 // Find the class template specialization declaration that
2067 // corresponds to these arguments.
2068 llvm::FoldingSetNodeID ID;
2069 ClassTemplateSpecializationDecl::Profile(ID, &ConvertedTemplateArgs[0],
2070 ConvertedTemplateArgs.size());
2071 void *InsertPos = 0;
2072 ClassTemplateSpecializationDecl *PrevDecl
2073 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
2074
2075 ClassTemplateSpecializationDecl *Specialization = 0;
2076
Douglas Gregor0d93f692009-02-25 22:02:03 +00002077 // Check whether we can declare a class template specialization in
2078 // the current scope.
2079 if (CheckClassTemplateSpecializationScope(ClassTemplate, PrevDecl,
2080 TemplateNameLoc,
Douglas Gregor90177912009-05-13 18:28:20 +00002081 SS.getRange(),
2082 /*ExplicitInstantiation=*/false))
Douglas Gregorc5d6fa72009-03-25 00:13:59 +00002083 return true;
Douglas Gregor0d93f692009-02-25 22:02:03 +00002084
Douglas Gregora08b6c72009-02-17 23:15:12 +00002085 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
2086 // Since the only prior class template specialization with these
2087 // arguments was referenced but not declared, reuse that
2088 // declaration node as our own, updating its source location to
2089 // reflect our new declaration.
Douglas Gregora08b6c72009-02-17 23:15:12 +00002090 Specialization = PrevDecl;
Douglas Gregor50113ca2009-02-25 22:18:32 +00002091 Specialization->setLocation(TemplateNameLoc);
Douglas Gregora08b6c72009-02-17 23:15:12 +00002092 PrevDecl = 0;
2093 } else {
2094 // Create a new class template specialization declaration node for
2095 // this explicit specialization.
2096 Specialization
2097 = ClassTemplateSpecializationDecl::Create(Context,
2098 ClassTemplate->getDeclContext(),
2099 TemplateNameLoc,
2100 ClassTemplate,
2101 &ConvertedTemplateArgs[0],
2102 ConvertedTemplateArgs.size(),
2103 PrevDecl);
2104
2105 if (PrevDecl) {
2106 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
2107 ClassTemplate->getSpecializations().GetOrInsertNode(Specialization);
2108 } else {
2109 ClassTemplate->getSpecializations().InsertNode(Specialization,
2110 InsertPos);
2111 }
2112 }
2113
2114 // Note that this is an explicit specialization.
2115 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
2116
2117 // Check that this isn't a redefinition of this specialization.
2118 if (TK == TK_Definition) {
2119 if (RecordDecl *Def = Specialization->getDefinition(Context)) {
2120 // FIXME: Should also handle explicit specialization after
2121 // implicit instantiation with a special diagnostic.
2122 SourceRange Range(TemplateNameLoc, RAngleLoc);
2123 Diag(TemplateNameLoc, diag::err_redefinition)
2124 << Specialization << Range;
2125 Diag(Def->getLocation(), diag::note_previous_definition);
2126 Specialization->setInvalidDecl();
Douglas Gregorc5d6fa72009-03-25 00:13:59 +00002127 return true;
Douglas Gregora08b6c72009-02-17 23:15:12 +00002128 }
2129 }
2130
Douglas Gregor9c7825b2009-02-26 22:19:44 +00002131 // Build the fully-sugared type for this class template
2132 // specialization as the user wrote in the specialization
2133 // itself. This means that we'll pretty-print the type retrieved
2134 // from the specialization's declaration the way that the user
2135 // actually wrote the specialization, rather than formatting the
2136 // name based on the "canonical" representation used to store the
2137 // template arguments in the specialization.
Douglas Gregor8c795a12009-03-19 00:39:20 +00002138 QualType WrittenTy
Douglas Gregordd13e842009-03-30 22:58:21 +00002139 = Context.getTemplateSpecializationType(Name,
2140 &TemplateArgs[0],
2141 TemplateArgs.size(),
Douglas Gregor8c795a12009-03-19 00:39:20 +00002142 Context.getTypeDeclType(Specialization));
Douglas Gregordd13e842009-03-30 22:58:21 +00002143 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00002144 TemplateArgsIn.release();
Douglas Gregora08b6c72009-02-17 23:15:12 +00002145
Douglas Gregor50113ca2009-02-25 22:18:32 +00002146 // C++ [temp.expl.spec]p9:
2147 // A template explicit specialization is in the scope of the
2148 // namespace in which the template was defined.
2149 //
2150 // We actually implement this paragraph where we set the semantic
2151 // context (in the creation of the ClassTemplateSpecializationDecl),
2152 // but we also maintain the lexical context where the actual
2153 // definition occurs.
Douglas Gregora08b6c72009-02-17 23:15:12 +00002154 Specialization->setLexicalDeclContext(CurContext);
2155
2156 // We may be starting the definition of this specialization.
2157 if (TK == TK_Definition)
2158 Specialization->startDefinition();
2159
2160 // Add the specialization into its lexical context, so that it can
2161 // be seen when iterating through the list of declarations in that
2162 // context. However, specializations are not found by name lookup.
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002163 CurContext->addDecl(Context, Specialization);
Chris Lattner5261d0c2009-03-28 19:18:32 +00002164 return DeclPtrTy::make(Specialization);
Douglas Gregora08b6c72009-02-17 23:15:12 +00002165}
Douglas Gregord3022602009-03-27 23:10:48 +00002166
Douglas Gregor96b6df92009-05-14 00:28:11 +00002167// Explicit instantiation of a class template specialization
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002168Sema::DeclResult
2169Sema::ActOnExplicitInstantiation(Scope *S, SourceLocation TemplateLoc,
2170 unsigned TagSpec,
2171 SourceLocation KWLoc,
2172 const CXXScopeSpec &SS,
2173 TemplateTy TemplateD,
2174 SourceLocation TemplateNameLoc,
2175 SourceLocation LAngleLoc,
2176 ASTTemplateArgsPtr TemplateArgsIn,
2177 SourceLocation *TemplateArgLocs,
2178 SourceLocation RAngleLoc,
2179 AttributeList *Attr) {
2180 // Find the class template we're specializing
2181 TemplateName Name = TemplateD.getAsVal<TemplateName>();
2182 ClassTemplateDecl *ClassTemplate
2183 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
2184
2185 // Check that the specialization uses the same tag kind as the
2186 // original template.
2187 TagDecl::TagKind Kind;
2188 switch (TagSpec) {
2189 default: assert(0 && "Unknown tag type!");
2190 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2191 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2192 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2193 }
Douglas Gregor625185c2009-05-14 16:41:31 +00002194 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
2195 Kind, KWLoc,
2196 *ClassTemplate->getIdentifier())) {
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002197 Diag(KWLoc, diag::err_use_with_wrong_tag)
2198 << ClassTemplate
2199 << CodeModificationHint::CreateReplacement(KWLoc,
2200 ClassTemplate->getTemplatedDecl()->getKindName());
2201 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
2202 diag::note_previous_use);
2203 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
2204 }
2205
Douglas Gregor90177912009-05-13 18:28:20 +00002206 // C++0x [temp.explicit]p2:
2207 // [...] An explicit instantiation shall appear in an enclosing
2208 // namespace of its template. [...]
2209 //
2210 // This is C++ DR 275.
2211 if (CheckClassTemplateSpecializationScope(ClassTemplate, 0,
2212 TemplateNameLoc,
2213 SS.getRange(),
2214 /*ExplicitInstantiation=*/true))
2215 return true;
2216
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002217 // Translate the parser's template argument list in our AST format.
2218 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
2219 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
2220
2221 // Check that the template argument list is well-formed for this
2222 // template.
2223 llvm::SmallVector<TemplateArgument, 16> ConvertedTemplateArgs;
2224 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
2225 &TemplateArgs[0], TemplateArgs.size(),
2226 RAngleLoc, ConvertedTemplateArgs))
2227 return true;
2228
2229 assert((ConvertedTemplateArgs.size() ==
2230 ClassTemplate->getTemplateParameters()->size()) &&
2231 "Converted template argument list is too short!");
2232
2233 // Find the class template specialization declaration that
2234 // corresponds to these arguments.
2235 llvm::FoldingSetNodeID ID;
2236 ClassTemplateSpecializationDecl::Profile(ID, &ConvertedTemplateArgs[0],
2237 ConvertedTemplateArgs.size());
2238 void *InsertPos = 0;
2239 ClassTemplateSpecializationDecl *PrevDecl
2240 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
2241
2242 ClassTemplateSpecializationDecl *Specialization = 0;
2243
Douglas Gregor90177912009-05-13 18:28:20 +00002244 bool SpecializationRequiresInstantiation = true;
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002245 if (PrevDecl) {
Douglas Gregor90177912009-05-13 18:28:20 +00002246 if (PrevDecl->getSpecializationKind() == TSK_ExplicitInstantiation) {
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002247 // This particular specialization has already been declared or
2248 // instantiated. We cannot explicitly instantiate it.
Douglas Gregor90177912009-05-13 18:28:20 +00002249 Diag(TemplateNameLoc, diag::err_explicit_instantiation_duplicate)
2250 << Context.getTypeDeclType(PrevDecl);
2251 Diag(PrevDecl->getLocation(),
2252 diag::note_previous_explicit_instantiation);
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002253 return DeclPtrTy::make(PrevDecl);
2254 }
2255
Douglas Gregor90177912009-05-13 18:28:20 +00002256 if (PrevDecl->getSpecializationKind() == TSK_ExplicitSpecialization) {
Douglas Gregor96b6df92009-05-14 00:28:11 +00002257 // C++ DR 259, C++0x [temp.explicit]p4:
Douglas Gregor90177912009-05-13 18:28:20 +00002258 // For a given set of template parameters, if an explicit
2259 // instantiation of a template appears after a declaration of
2260 // an explicit specialization for that template, the explicit
2261 // instantiation has no effect.
2262 if (!getLangOptions().CPlusPlus0x) {
2263 Diag(TemplateNameLoc,
2264 diag::ext_explicit_instantiation_after_specialization)
2265 << Context.getTypeDeclType(PrevDecl);
2266 Diag(PrevDecl->getLocation(),
2267 diag::note_previous_template_specialization);
2268 }
2269
2270 // Create a new class template specialization declaration node
2271 // for this explicit specialization. This node is only used to
2272 // record the existence of this explicit instantiation for
2273 // accurate reproduction of the source code; we don't actually
2274 // use it for anything, since it is semantically irrelevant.
2275 Specialization
2276 = ClassTemplateSpecializationDecl::Create(Context,
2277 ClassTemplate->getDeclContext(),
2278 TemplateNameLoc,
2279 ClassTemplate,
2280 &ConvertedTemplateArgs[0],
2281 ConvertedTemplateArgs.size(),
2282 0);
2283 Specialization->setLexicalDeclContext(CurContext);
2284 CurContext->addDecl(Context, Specialization);
2285 return DeclPtrTy::make(Specialization);
2286 }
2287
2288 // If we have already (implicitly) instantiated this
2289 // specialization, there is less work to do.
2290 if (PrevDecl->getSpecializationKind() == TSK_ImplicitInstantiation)
2291 SpecializationRequiresInstantiation = false;
2292
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002293 // Since the only prior class template specialization with these
2294 // arguments was referenced but not declared, reuse that
2295 // declaration node as our own, updating its source location to
2296 // reflect our new declaration.
2297 Specialization = PrevDecl;
2298 Specialization->setLocation(TemplateNameLoc);
2299 PrevDecl = 0;
2300 } else {
2301 // Create a new class template specialization declaration node for
2302 // this explicit specialization.
2303 Specialization
2304 = ClassTemplateSpecializationDecl::Create(Context,
2305 ClassTemplate->getDeclContext(),
2306 TemplateNameLoc,
2307 ClassTemplate,
2308 &ConvertedTemplateArgs[0],
2309 ConvertedTemplateArgs.size(),
2310 0);
2311
2312 ClassTemplate->getSpecializations().InsertNode(Specialization,
2313 InsertPos);
2314 }
2315
2316 // Build the fully-sugared type for this explicit instantiation as
2317 // the user wrote in the explicit instantiation itself. This means
2318 // that we'll pretty-print the type retrieved from the
2319 // specialization's declaration the way that the user actually wrote
2320 // the explicit instantiation, rather than formatting the name based
2321 // on the "canonical" representation used to store the template
2322 // arguments in the specialization.
2323 QualType WrittenTy
2324 = Context.getTemplateSpecializationType(Name,
2325 &TemplateArgs[0],
2326 TemplateArgs.size(),
2327 Context.getTypeDeclType(Specialization));
2328 Specialization->setTypeAsWritten(WrittenTy);
2329 TemplateArgsIn.release();
2330
2331 // Add the explicit instantiation into its lexical context. However,
2332 // since explicit instantiations are never found by name lookup, we
2333 // just put it into the declaration context directly.
2334 Specialization->setLexicalDeclContext(CurContext);
2335 CurContext->addDecl(Context, Specialization);
2336
2337 // C++ [temp.explicit]p3:
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002338 // A definition of a class template or class member template
2339 // shall be in scope at the point of the explicit instantiation of
2340 // the class template or class member template.
2341 //
2342 // This check comes when we actually try to perform the
2343 // instantiation.
Douglas Gregor556d8c72009-05-15 17:59:04 +00002344 if (SpecializationRequiresInstantiation)
2345 InstantiateClassTemplateSpecialization(Specialization, true);
2346 else {
2347 // Instantiate the members of this class template specialization.
2348 InstantiatingTemplate Inst(*this, TemplateLoc, Specialization);
2349 InstantiateClassTemplateSpecializationMembers(TemplateLoc, Specialization);
2350 }
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002351
2352 return DeclPtrTy::make(Specialization);
2353}
2354
Douglas Gregor96b6df92009-05-14 00:28:11 +00002355// Explicit instantiation of a member class of a class template.
2356Sema::DeclResult
2357Sema::ActOnExplicitInstantiation(Scope *S, SourceLocation TemplateLoc,
2358 unsigned TagSpec,
2359 SourceLocation KWLoc,
2360 const CXXScopeSpec &SS,
2361 IdentifierInfo *Name,
2362 SourceLocation NameLoc,
2363 AttributeList *Attr) {
2364
2365 DeclPtrTy TagD = ActOnTag(S, TagSpec, Action::TK_Reference,
2366 KWLoc, SS, Name, NameLoc, Attr, AS_none);
2367 if (!TagD)
2368 return true;
2369
2370 TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
2371 if (Tag->isEnum()) {
2372 Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
2373 << Context.getTypeDeclType(Tag);
2374 return true;
2375 }
2376
2377 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
2378 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
2379 if (!Pattern) {
2380 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
2381 << Context.getTypeDeclType(Record);
2382 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
2383 return true;
2384 }
2385
2386 // C++0x [temp.explicit]p2:
2387 // [...] An explicit instantiation shall appear in an enclosing
2388 // namespace of its template. [...]
2389 //
2390 // This is C++ DR 275.
2391 if (getLangOptions().CPlusPlus0x) {
2392 // FIXME: In C++98, we would like to turn these errors into
2393 // warnings, dependent on a -Wc++0x flag.
2394 DeclContext *PatternContext
2395 = Pattern->getDeclContext()->getEnclosingNamespaceContext();
2396 if (!CurContext->Encloses(PatternContext)) {
2397 Diag(TemplateLoc, diag::err_explicit_instantiation_out_of_scope)
2398 << Record << cast<NamedDecl>(PatternContext) << SS.getRange();
2399 Diag(Pattern->getLocation(), diag::note_previous_declaration);
2400 }
2401 }
2402
Douglas Gregor96b6df92009-05-14 00:28:11 +00002403 if (!Record->getDefinition(Context)) {
2404 // If the class has a definition, instantiate it (and all of its
2405 // members, recursively).
2406 Pattern = cast_or_null<CXXRecordDecl>(Pattern->getDefinition(Context));
2407 if (Pattern && InstantiateClass(TemplateLoc, Record, Pattern,
Douglas Gregor5f62c5e2009-05-14 23:26:13 +00002408 getTemplateInstantiationArgs(Record),
Douglas Gregor96b6df92009-05-14 00:28:11 +00002409 /*ExplicitInstantiation=*/true))
2410 return true;
2411 } else {
2412 // Instantiate all of the members of class.
2413 InstantiatingTemplate Inst(*this, TemplateLoc, Record);
2414 InstantiateClassMembers(TemplateLoc, Record,
Douglas Gregor5f62c5e2009-05-14 23:26:13 +00002415 getTemplateInstantiationArgs(Record));
Douglas Gregor96b6df92009-05-14 00:28:11 +00002416 }
2417
2418 // FIXME: We don't have any representation for explicit
2419 // instantiations of member classes. Such a representation is not
2420 // needed for compilation, but it should be available for clients
2421 // that want to see all of the declarations in the source code.
2422 return TagD;
2423}
2424
Douglas Gregord3022602009-03-27 23:10:48 +00002425Sema::TypeResult
2426Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
2427 const IdentifierInfo &II, SourceLocation IdLoc) {
2428 NestedNameSpecifier *NNS
2429 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
2430 if (!NNS)
2431 return true;
2432
2433 QualType T = CheckTypenameType(NNS, II, SourceRange(TypenameLoc, IdLoc));
Douglas Gregord7cb0372009-04-01 21:51:26 +00002434 if (T.isNull())
2435 return true;
Douglas Gregord3022602009-03-27 23:10:48 +00002436 return T.getAsOpaquePtr();
2437}
2438
Douglas Gregor77da5802009-04-01 00:28:59 +00002439Sema::TypeResult
2440Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
2441 SourceLocation TemplateLoc, TypeTy *Ty) {
2442 QualType T = QualType::getFromOpaquePtr(Ty);
2443 NestedNameSpecifier *NNS
2444 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
2445 const TemplateSpecializationType *TemplateId
2446 = T->getAsTemplateSpecializationType();
2447 assert(TemplateId && "Expected a template specialization type");
2448
2449 if (NNS->isDependent())
2450 return Context.getTypenameType(NNS, TemplateId).getAsOpaquePtr();
2451
2452 return Context.getQualifiedNameType(NNS, T).getAsOpaquePtr();
2453}
2454
Douglas Gregord3022602009-03-27 23:10:48 +00002455/// \brief Build the type that describes a C++ typename specifier,
2456/// e.g., "typename T::type".
2457QualType
2458Sema::CheckTypenameType(NestedNameSpecifier *NNS, const IdentifierInfo &II,
2459 SourceRange Range) {
Douglas Gregor3eb20702009-05-11 19:58:34 +00002460 CXXRecordDecl *CurrentInstantiation = 0;
2461 if (NNS->isDependent()) {
2462 CurrentInstantiation = getCurrentInstantiationOf(NNS);
Douglas Gregord3022602009-03-27 23:10:48 +00002463
Douglas Gregor3eb20702009-05-11 19:58:34 +00002464 // If the nested-name-specifier does not refer to the current
2465 // instantiation, then build a typename type.
2466 if (!CurrentInstantiation)
2467 return Context.getTypenameType(NNS, &II);
2468 }
Douglas Gregord3022602009-03-27 23:10:48 +00002469
Douglas Gregor3eb20702009-05-11 19:58:34 +00002470 DeclContext *Ctx = 0;
2471
2472 if (CurrentInstantiation)
2473 Ctx = CurrentInstantiation;
2474 else {
2475 CXXScopeSpec SS;
2476 SS.setScopeRep(NNS);
2477 SS.setRange(Range);
2478 if (RequireCompleteDeclContext(SS))
2479 return QualType();
2480
2481 Ctx = computeDeclContext(SS);
2482 }
Douglas Gregord3022602009-03-27 23:10:48 +00002483 assert(Ctx && "No declaration context?");
2484
2485 DeclarationName Name(&II);
2486 LookupResult Result = LookupQualifiedName(Ctx, Name, LookupOrdinaryName,
2487 false);
2488 unsigned DiagID = 0;
2489 Decl *Referenced = 0;
2490 switch (Result.getKind()) {
2491 case LookupResult::NotFound:
2492 if (Ctx->isTranslationUnit())
2493 DiagID = diag::err_typename_nested_not_found_global;
2494 else
2495 DiagID = diag::err_typename_nested_not_found;
2496 break;
2497
2498 case LookupResult::Found:
2499 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getAsDecl())) {
2500 // We found a type. Build a QualifiedNameType, since the
2501 // typename-specifier was just sugar. FIXME: Tell
2502 // QualifiedNameType that it has a "typename" prefix.
2503 return Context.getQualifiedNameType(NNS, Context.getTypeDeclType(Type));
2504 }
2505
2506 DiagID = diag::err_typename_nested_not_type;
2507 Referenced = Result.getAsDecl();
2508 break;
2509
2510 case LookupResult::FoundOverloaded:
2511 DiagID = diag::err_typename_nested_not_type;
2512 Referenced = *Result.begin();
2513 break;
2514
2515 case LookupResult::AmbiguousBaseSubobjectTypes:
2516 case LookupResult::AmbiguousBaseSubobjects:
2517 case LookupResult::AmbiguousReference:
2518 DiagnoseAmbiguousLookup(Result, Name, Range.getEnd(), Range);
2519 return QualType();
2520 }
2521
2522 // If we get here, it's because name lookup did not find a
2523 // type. Emit an appropriate diagnostic and return an error.
2524 if (NamedDecl *NamedCtx = dyn_cast<NamedDecl>(Ctx))
2525 Diag(Range.getEnd(), DiagID) << Range << Name << NamedCtx;
2526 else
2527 Diag(Range.getEnd(), DiagID) << Range << Name;
2528 if (Referenced)
2529 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
2530 << Name;
2531 return QualType();
2532}