blob: 97812046f7f2c66641b065a7b9461cc9c80bdbe6 [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()) {
Argiris Kirtzidis17c7cab2009-07-18 00:34:25 +000059 Record = cast<CXXRecordDecl>(Record->getCanonicalDecl());
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 Gregor9614dad2009-06-24 00:23:40 +000070 // FIXME: What follows is a slightly less gross hack than what used to
71 // follow.
Douglas Gregor2fa10442008-12-18 19:37:40 +000072 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(IIDecl)) {
Douglas Gregor9614dad2009-06-24 00:23:40 +000073 if (FD->getDescribedFunctionTemplate()) {
Douglas Gregordd13e842009-03-30 22:58:21 +000074 TemplateResult = TemplateTy::make(FD);
Douglas Gregor8e458f42009-02-09 18:46:07 +000075 return TNK_Function_template;
76 }
Douglas Gregor2fa10442008-12-18 19:37:40 +000077 } else if (OverloadedFunctionDecl *Ovl
78 = dyn_cast<OverloadedFunctionDecl>(IIDecl)) {
79 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
80 FEnd = Ovl->function_end();
81 F != FEnd; ++F) {
Douglas Gregorb60eb752009-06-25 22:08:12 +000082 if (isa<FunctionTemplateDecl>(*F)) {
Douglas Gregordd13e842009-03-30 22:58:21 +000083 TemplateResult = TemplateTy::make(Ovl);
Douglas Gregor8e458f42009-02-09 18:46:07 +000084 return TNK_Function_template;
85 }
Douglas Gregor2fa10442008-12-18 19:37:40 +000086 }
87 }
Douglas Gregordd13e842009-03-30 22:58:21 +000088
89 if (TNK != TNK_Non_template) {
90 if (SS && SS->isSet() && !SS->isInvalid()) {
91 NestedNameSpecifier *Qualifier
92 = static_cast<NestedNameSpecifier *>(SS->getScopeRep());
93 TemplateResult
94 = TemplateTy::make(Context.getQualifiedTemplateName(Qualifier,
95 false,
96 Template));
97 } else
98 TemplateResult = TemplateTy::make(TemplateName(Template));
99 }
Douglas Gregor2fa10442008-12-18 19:37:40 +0000100 }
Douglas Gregordd13e842009-03-30 22:58:21 +0000101 return TNK;
Douglas Gregor2fa10442008-12-18 19:37:40 +0000102}
103
Douglas Gregordd861062008-12-05 18:15:24 +0000104/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
105/// that the template parameter 'PrevDecl' is being shadowed by a new
106/// declaration at location Loc. Returns true to indicate that this is
107/// an error, and false otherwise.
108bool Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
Douglas Gregor2715a1f2008-12-08 18:40:42 +0000109 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregordd861062008-12-05 18:15:24 +0000110
111 // Microsoft Visual C++ permits template parameters to be shadowed.
112 if (getLangOptions().Microsoft)
113 return false;
114
115 // C++ [temp.local]p4:
116 // A template-parameter shall not be redeclared within its
117 // scope (including nested scopes).
118 Diag(Loc, diag::err_template_param_shadow)
119 << cast<NamedDecl>(PrevDecl)->getDeclName();
120 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
121 return true;
122}
123
Douglas Gregored3a3982009-03-03 04:44:36 +0000124/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregor279272e2009-02-04 19:02:06 +0000125/// the parameter D to reference the templated declaration and return a pointer
126/// to the template declaration. Otherwise, do nothing to D and return null.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000127TemplateDecl *Sema::AdjustDeclIfTemplate(DeclPtrTy &D) {
128 if (TemplateDecl *Temp = dyn_cast<TemplateDecl>(D.getAs<Decl>())) {
129 D = DeclPtrTy::make(Temp->getTemplatedDecl());
Douglas Gregor279272e2009-02-04 19:02:06 +0000130 return Temp;
131 }
132 return 0;
133}
134
Douglas Gregordd861062008-12-05 18:15:24 +0000135/// ActOnTypeParameter - Called when a C++ template type parameter
136/// (e.g., "typename T") has been parsed. Typename specifies whether
137/// the keyword "typename" was used to declare the type parameter
138/// (otherwise, "class" was used), and KeyLoc is the location of the
139/// "class" or "typename" keyword. ParamName is the name of the
140/// parameter (NULL indicates an unnamed template parameter) and
141/// ParamName is the location of the parameter name (if any).
142/// If the type parameter has a default argument, it will be added
143/// later via ActOnTypeParameterDefault.
Anders Carlsson9c85fa02009-06-12 19:58:00 +0000144Sema::DeclPtrTy Sema::ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis,
145 SourceLocation EllipsisLoc,
Chris Lattner5261d0c2009-03-28 19:18:32 +0000146 SourceLocation KeyLoc,
147 IdentifierInfo *ParamName,
148 SourceLocation ParamNameLoc,
149 unsigned Depth, unsigned Position) {
Douglas Gregordd861062008-12-05 18:15:24 +0000150 assert(S->isTemplateParamScope() &&
151 "Template type parameter not in template parameter scope!");
152 bool Invalid = false;
153
154 if (ParamName) {
Douglas Gregor09be81b2009-02-04 17:27:36 +0000155 NamedDecl *PrevDecl = LookupName(S, ParamName, LookupTagName);
Douglas Gregor2715a1f2008-12-08 18:40:42 +0000156 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregordd861062008-12-05 18:15:24 +0000157 Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc,
158 PrevDecl);
159 }
160
Douglas Gregord406b032009-02-06 22:42:48 +0000161 SourceLocation Loc = ParamNameLoc;
162 if (!ParamName)
163 Loc = KeyLoc;
164
Douglas Gregordd861062008-12-05 18:15:24 +0000165 TemplateTypeParmDecl *Param
Douglas Gregord406b032009-02-06 22:42:48 +0000166 = TemplateTypeParmDecl::Create(Context, CurContext, Loc,
Anders Carlssoneebbf9a2009-06-12 22:23:22 +0000167 Depth, Position, ParamName, Typename,
168 Ellipsis);
Douglas Gregordd861062008-12-05 18:15:24 +0000169 if (Invalid)
170 Param->setInvalidDecl();
171
172 if (ParamName) {
173 // Add the template parameter into the current scope.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000174 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregordd861062008-12-05 18:15:24 +0000175 IdResolver.AddDecl(Param);
176 }
177
Chris Lattner5261d0c2009-03-28 19:18:32 +0000178 return DeclPtrTy::make(Param);
Douglas Gregordd861062008-12-05 18:15:24 +0000179}
180
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000181/// ActOnTypeParameterDefault - Adds a default argument (the type
182/// Default) to the given template type parameter (TypeParam).
Chris Lattner5261d0c2009-03-28 19:18:32 +0000183void Sema::ActOnTypeParameterDefault(DeclPtrTy TypeParam,
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000184 SourceLocation EqualLoc,
185 SourceLocation DefaultLoc,
186 TypeTy *DefaultT) {
187 TemplateTypeParmDecl *Parm
Chris Lattner5261d0c2009-03-28 19:18:32 +0000188 = cast<TemplateTypeParmDecl>(TypeParam.getAs<Decl>());
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000189 QualType Default = QualType::getFromOpaquePtr(DefaultT);
190
Anders Carlssona2333782009-06-12 22:30:13 +0000191 // C++0x [temp.param]p9:
192 // A default template-argument may be specified for any kind of
193 // template-parameter that is not a template parameter pack.
194 if (Parm->isParameterPack()) {
195 Diag(DefaultLoc, diag::err_template_param_pack_default_arg);
Anders Carlssona2333782009-06-12 22:30:13 +0000196 return;
197 }
198
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000199 // C++ [temp.param]p14:
200 // A template-parameter shall not be used in its own default argument.
201 // FIXME: Implement this check! Needs a recursive walk over the types.
202
203 // Check the template argument itself.
204 if (CheckTemplateArgument(Parm, Default, DefaultLoc)) {
205 Parm->setInvalidDecl();
206 return;
207 }
208
209 Parm->setDefaultArgument(Default, DefaultLoc, false);
210}
211
Douglas Gregored3a3982009-03-03 04:44:36 +0000212/// \brief Check that the type of a non-type template parameter is
213/// well-formed.
214///
215/// \returns the (possibly-promoted) parameter type if valid;
216/// otherwise, produces a diagnostic and returns a NULL type.
217QualType
218Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
219 // C++ [temp.param]p4:
220 //
221 // A non-type template-parameter shall have one of the following
222 // (optionally cv-qualified) types:
223 //
224 // -- integral or enumeration type,
225 if (T->isIntegralType() || T->isEnumeralType() ||
226 // -- pointer to object or pointer to function,
227 (T->isPointerType() &&
Ted Kremenekd9b39bf2009-07-17 17:50:17 +0000228 (T->getAsPointerType()->getPointeeType()->isObjectType() ||
229 T->getAsPointerType()->getPointeeType()->isFunctionType())) ||
Douglas Gregored3a3982009-03-03 04:44:36 +0000230 // -- reference to object or reference to function,
231 T->isReferenceType() ||
232 // -- pointer to member.
233 T->isMemberPointerType() ||
234 // If T is a dependent type, we can't do the check now, so we
235 // assume that it is well-formed.
236 T->isDependentType())
237 return T;
238 // C++ [temp.param]p8:
239 //
240 // A non-type template-parameter of type "array of T" or
241 // "function returning T" is adjusted to be of type "pointer to
242 // T" or "pointer to function returning T", respectively.
243 else if (T->isArrayType())
244 // FIXME: Keep the type prior to promotion?
245 return Context.getArrayDecayedType(T);
246 else if (T->isFunctionType())
247 // FIXME: Keep the type prior to promotion?
248 return Context.getPointerType(T);
249
250 Diag(Loc, diag::err_template_nontype_parm_bad_type)
251 << T;
252
253 return QualType();
254}
255
Douglas Gregordd861062008-12-05 18:15:24 +0000256/// ActOnNonTypeTemplateParameter - Called when a C++ non-type
257/// template parameter (e.g., "int Size" in "template<int Size>
258/// class Array") has been parsed. S is the current scope and D is
259/// the parsed declarator.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000260Sema::DeclPtrTy Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
261 unsigned Depth,
262 unsigned Position) {
Douglas Gregordd861062008-12-05 18:15:24 +0000263 QualType T = GetTypeForDeclarator(D, S);
264
Douglas Gregor279272e2009-02-04 19:02:06 +0000265 assert(S->isTemplateParamScope() &&
266 "Non-type template parameter not in template parameter scope!");
Douglas Gregordd861062008-12-05 18:15:24 +0000267 bool Invalid = false;
268
269 IdentifierInfo *ParamName = D.getIdentifier();
270 if (ParamName) {
Douglas Gregor09be81b2009-02-04 17:27:36 +0000271 NamedDecl *PrevDecl = LookupName(S, ParamName, LookupTagName);
Douglas Gregor2715a1f2008-12-08 18:40:42 +0000272 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregordd861062008-12-05 18:15:24 +0000273 Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
Douglas Gregor279272e2009-02-04 19:02:06 +0000274 PrevDecl);
Douglas Gregordd861062008-12-05 18:15:24 +0000275 }
276
Douglas Gregored3a3982009-03-03 04:44:36 +0000277 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
Douglas Gregor8b90e8e2009-03-09 16:46:39 +0000278 if (T.isNull()) {
Douglas Gregored3a3982009-03-03 04:44:36 +0000279 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregor8b90e8e2009-03-09 16:46:39 +0000280 Invalid = true;
281 }
Douglas Gregor62cdc792009-02-10 17:43:50 +0000282
Douglas Gregordd861062008-12-05 18:15:24 +0000283 NonTypeTemplateParmDecl *Param
284 = NonTypeTemplateParmDecl::Create(Context, CurContext, D.getIdentifierLoc(),
Douglas Gregor279272e2009-02-04 19:02:06 +0000285 Depth, Position, ParamName, T);
Douglas Gregordd861062008-12-05 18:15:24 +0000286 if (Invalid)
287 Param->setInvalidDecl();
288
289 if (D.getIdentifier()) {
290 // Add the template parameter into the current scope.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000291 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregordd861062008-12-05 18:15:24 +0000292 IdResolver.AddDecl(Param);
293 }
Chris Lattner5261d0c2009-03-28 19:18:32 +0000294 return DeclPtrTy::make(Param);
Douglas Gregordd861062008-12-05 18:15:24 +0000295}
Douglas Gregor52473432008-12-24 02:52:09 +0000296
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000297/// \brief Adds a default argument to the given non-type template
298/// parameter.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000299void Sema::ActOnNonTypeTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000300 SourceLocation EqualLoc,
301 ExprArg DefaultE) {
302 NonTypeTemplateParmDecl *TemplateParm
Chris Lattner5261d0c2009-03-28 19:18:32 +0000303 = cast<NonTypeTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000304 Expr *Default = static_cast<Expr *>(DefaultE.get());
305
306 // C++ [temp.param]p14:
307 // A template-parameter shall not be used in its own default argument.
308 // FIXME: Implement this check! Needs a recursive walk over the types.
309
310 // Check the well-formedness of the default template argument.
Douglas Gregor8f378a92009-06-11 18:10:32 +0000311 TemplateArgument Converted;
312 if (CheckTemplateArgument(TemplateParm, TemplateParm->getType(), Default,
313 Converted)) {
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000314 TemplateParm->setInvalidDecl();
315 return;
316 }
317
Anders Carlsson39ecdcf2009-05-01 19:49:17 +0000318 TemplateParm->setDefaultArgument(DefaultE.takeAs<Expr>());
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000319}
320
Douglas Gregor279272e2009-02-04 19:02:06 +0000321
322/// ActOnTemplateTemplateParameter - Called when a C++ template template
323/// parameter (e.g. T in template <template <typename> class T> class array)
324/// has been parsed. S is the current scope.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000325Sema::DeclPtrTy Sema::ActOnTemplateTemplateParameter(Scope* S,
326 SourceLocation TmpLoc,
327 TemplateParamsTy *Params,
328 IdentifierInfo *Name,
329 SourceLocation NameLoc,
330 unsigned Depth,
331 unsigned Position)
Douglas Gregor279272e2009-02-04 19:02:06 +0000332{
333 assert(S->isTemplateParamScope() &&
334 "Template template parameter not in template parameter scope!");
335
336 // Construct the parameter object.
337 TemplateTemplateParmDecl *Param =
338 TemplateTemplateParmDecl::Create(Context, CurContext, TmpLoc, Depth,
339 Position, Name,
340 (TemplateParameterList*)Params);
341
342 // Make sure the parameter is valid.
343 // FIXME: Decl object is not currently invalidated anywhere so this doesn't
344 // do anything yet. However, if the template parameter list or (eventual)
345 // default value is ever invalidated, that will propagate here.
346 bool Invalid = false;
347 if (Invalid) {
348 Param->setInvalidDecl();
349 }
350
351 // If the tt-param has a name, then link the identifier into the scope
352 // and lookup mechanisms.
353 if (Name) {
Chris Lattner5261d0c2009-03-28 19:18:32 +0000354 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor279272e2009-02-04 19:02:06 +0000355 IdResolver.AddDecl(Param);
356 }
357
Chris Lattner5261d0c2009-03-28 19:18:32 +0000358 return DeclPtrTy::make(Param);
Douglas Gregor279272e2009-02-04 19:02:06 +0000359}
360
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000361/// \brief Adds a default argument to the given template template
362/// parameter.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000363void Sema::ActOnTemplateTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000364 SourceLocation EqualLoc,
365 ExprArg DefaultE) {
366 TemplateTemplateParmDecl *TemplateParm
Chris Lattner5261d0c2009-03-28 19:18:32 +0000367 = cast<TemplateTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000368
369 // Since a template-template parameter's default argument is an
370 // id-expression, it must be a DeclRefExpr.
371 DeclRefExpr *Default
372 = cast<DeclRefExpr>(static_cast<Expr *>(DefaultE.get()));
373
374 // C++ [temp.param]p14:
375 // A template-parameter shall not be used in its own default argument.
376 // FIXME: Implement this check! Needs a recursive walk over the types.
377
378 // Check the well-formedness of the template argument.
379 if (!isa<TemplateDecl>(Default->getDecl())) {
380 Diag(Default->getSourceRange().getBegin(),
381 diag::err_template_arg_must_be_template)
382 << Default->getSourceRange();
383 TemplateParm->setInvalidDecl();
384 return;
385 }
386 if (CheckTemplateArgument(TemplateParm, Default)) {
387 TemplateParm->setInvalidDecl();
388 return;
389 }
390
391 DefaultE.release();
392 TemplateParm->setDefaultArgument(Default);
393}
394
Douglas Gregor52473432008-12-24 02:52:09 +0000395/// ActOnTemplateParameterList - Builds a TemplateParameterList that
396/// contains the template parameters in Params/NumParams.
397Sema::TemplateParamsTy *
398Sema::ActOnTemplateParameterList(unsigned Depth,
399 SourceLocation ExportLoc,
400 SourceLocation TemplateLoc,
401 SourceLocation LAngleLoc,
Chris Lattner5261d0c2009-03-28 19:18:32 +0000402 DeclPtrTy *Params, unsigned NumParams,
Douglas Gregor52473432008-12-24 02:52:09 +0000403 SourceLocation RAngleLoc) {
404 if (ExportLoc.isValid())
405 Diag(ExportLoc, diag::note_template_export_unsupported);
406
Douglas Gregord406b032009-02-06 22:42:48 +0000407 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
408 (Decl**)Params, NumParams, RAngleLoc);
Douglas Gregor52473432008-12-24 02:52:09 +0000409}
Douglas Gregor279272e2009-02-04 19:02:06 +0000410
Douglas Gregorc5d6fa72009-03-25 00:13:59 +0000411Sema::DeclResult
Douglas Gregor95254bc2009-07-23 16:36:45 +0000412Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagKind TK,
Douglas Gregord406b032009-02-06 22:42:48 +0000413 SourceLocation KWLoc, const CXXScopeSpec &SS,
414 IdentifierInfo *Name, SourceLocation NameLoc,
415 AttributeList *Attr,
Anders Carlssoned20fb92009-03-26 00:52:18 +0000416 MultiTemplateParamsArg TemplateParameterLists,
417 AccessSpecifier AS) {
Douglas Gregord406b032009-02-06 22:42:48 +0000418 assert(TemplateParameterLists.size() > 0 && "No template parameter lists?");
419 assert(TK != TK_Reference && "Can only declare or define class templates");
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000420 bool Invalid = false;
Douglas Gregord406b032009-02-06 22:42:48 +0000421
422 // Check that we can declare a template here.
423 if (CheckTemplateDeclScope(S, TemplateParameterLists))
Douglas Gregorc5d6fa72009-03-25 00:13:59 +0000424 return true;
Douglas Gregord406b032009-02-06 22:42:48 +0000425
426 TagDecl::TagKind Kind;
427 switch (TagSpec) {
428 default: assert(0 && "Unknown tag type!");
429 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
430 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
431 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
432 }
433
434 // There is no such thing as an unnamed class template.
435 if (!Name) {
436 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregorc5d6fa72009-03-25 00:13:59 +0000437 return true;
Douglas Gregord406b032009-02-06 22:42:48 +0000438 }
439
440 // Find any previous declaration with this name.
441 LookupResult Previous = LookupParsedName(S, &SS, Name, LookupOrdinaryName,
442 true);
443 assert(!Previous.isAmbiguous() && "Ambiguity in class template redecl?");
444 NamedDecl *PrevDecl = 0;
445 if (Previous.begin() != Previous.end())
446 PrevDecl = *Previous.begin();
447
Douglas Gregor23521802009-06-17 23:37:01 +0000448 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
449 PrevDecl = 0;
450
Douglas Gregord406b032009-02-06 22:42:48 +0000451 DeclContext *SemanticContext = CurContext;
452 if (SS.isNotEmpty() && !SS.isInvalid()) {
Douglas Gregor734b4ba2009-03-19 00:18:19 +0000453 SemanticContext = computeDeclContext(SS);
Douglas Gregord406b032009-02-06 22:42:48 +0000454
Mike Stumpe127ae32009-05-16 07:39:55 +0000455 // FIXME: need to match up several levels of template parameter lists here.
Douglas Gregord406b032009-02-06 22:42:48 +0000456 }
457
458 // FIXME: member templates!
459 TemplateParameterList *TemplateParams
460 = static_cast<TemplateParameterList *>(*TemplateParameterLists.release());
461
462 // If there is a previous declaration with the same name, check
463 // whether this is a valid redeclaration.
464 ClassTemplateDecl *PrevClassTemplate
465 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
466 if (PrevClassTemplate) {
467 // Ensure that the template parameter lists are compatible.
468 if (!TemplateParameterListsAreEqual(TemplateParams,
469 PrevClassTemplate->getTemplateParameters(),
470 /*Complain=*/true))
Douglas Gregorc5d6fa72009-03-25 00:13:59 +0000471 return true;
Douglas Gregord406b032009-02-06 22:42:48 +0000472
473 // C++ [temp.class]p4:
474 // In a redeclaration, partial specialization, explicit
475 // specialization or explicit instantiation of a class template,
476 // the class-key shall agree in kind with the original class
477 // template declaration (7.1.5.3).
478 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Douglas Gregor625185c2009-05-14 16:41:31 +0000479 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind, KWLoc, *Name)) {
Douglas Gregor3faaa812009-04-01 23:51:29 +0000480 Diag(KWLoc, diag::err_use_with_wrong_tag)
481 << Name
482 << CodeModificationHint::CreateReplacement(KWLoc,
483 PrevRecordDecl->getKindName());
Douglas Gregord406b032009-02-06 22:42:48 +0000484 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregor3faaa812009-04-01 23:51:29 +0000485 Kind = PrevRecordDecl->getTagKind();
Douglas Gregord406b032009-02-06 22:42:48 +0000486 }
487
Douglas Gregord406b032009-02-06 22:42:48 +0000488 // Check for redefinition of this class template.
489 if (TK == TK_Definition) {
490 if (TagDecl *Def = PrevRecordDecl->getDefinition(Context)) {
491 Diag(NameLoc, diag::err_redefinition) << Name;
492 Diag(Def->getLocation(), diag::note_previous_definition);
493 // FIXME: Would it make sense to try to "forget" the previous
494 // definition, as part of error recovery?
Douglas Gregorc5d6fa72009-03-25 00:13:59 +0000495 return true;
Douglas Gregord406b032009-02-06 22:42:48 +0000496 }
497 }
498 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
499 // Maybe we will complain about the shadowed template parameter.
500 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
501 // Just pretend that we didn't see the previous declaration.
502 PrevDecl = 0;
503 } else if (PrevDecl) {
504 // C++ [temp]p5:
505 // A class template shall not have the same name as any other
506 // template, class, function, object, enumeration, enumerator,
507 // namespace, or type in the same scope (3.3), except as specified
508 // in (14.5.4).
509 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
510 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregorc5d6fa72009-03-25 00:13:59 +0000511 return true;
Douglas Gregord406b032009-02-06 22:42:48 +0000512 }
513
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000514 // Check the template parameter list of this declaration, possibly
515 // merging in the template parameter list from the previous class
516 // template declaration.
517 if (CheckTemplateParameterList(TemplateParams,
518 PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0))
519 Invalid = true;
520
Douglas Gregor9054f982009-05-10 22:57:19 +0000521 // FIXME: If we had a scope specifier, we better have a previous template
Douglas Gregord406b032009-02-06 22:42:48 +0000522 // declaration!
523
Douglas Gregor55216ac2009-03-26 00:10:35 +0000524 CXXRecordDecl *NewClass =
Douglas Gregor9060d0e2009-07-21 14:46:17 +0000525 CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name, KWLoc,
Douglas Gregord406b032009-02-06 22:42:48 +0000526 PrevClassTemplate?
Douglas Gregor12aed0b2009-05-15 19:11:46 +0000527 PrevClassTemplate->getTemplatedDecl() : 0,
528 /*DelayTypeCreation=*/true);
Douglas Gregord406b032009-02-06 22:42:48 +0000529
530 ClassTemplateDecl *NewTemplate
531 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
532 DeclarationName(Name), TemplateParams,
Douglas Gregor47bde7c2009-03-19 17:26:29 +0000533 NewClass, PrevClassTemplate);
Douglas Gregor55216ac2009-03-26 00:10:35 +0000534 NewClass->setDescribedClassTemplate(NewTemplate);
535
Douglas Gregor12aed0b2009-05-15 19:11:46 +0000536 // Build the type for the class template declaration now.
537 QualType T =
538 Context.getTypeDeclType(NewClass,
539 PrevClassTemplate?
540 PrevClassTemplate->getTemplatedDecl() : 0);
541 assert(T->isDependentType() && "Class template type is not dependent?");
542 (void)T;
543
Anders Carlsson4ca43492009-03-26 01:24:28 +0000544 // Set the access specifier.
545 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
546
Douglas Gregord406b032009-02-06 22:42:48 +0000547 // Set the lexical context of these templates
548 NewClass->setLexicalDeclContext(CurContext);
549 NewTemplate->setLexicalDeclContext(CurContext);
550
551 if (TK == TK_Definition)
552 NewClass->startDefinition();
553
554 if (Attr)
Douglas Gregor2a2e0402009-06-17 21:51:59 +0000555 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregord406b032009-02-06 22:42:48 +0000556
557 PushOnScopeChains(NewTemplate, S);
558
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000559 if (Invalid) {
560 NewTemplate->setInvalidDecl();
561 NewClass->setInvalidDecl();
562 }
Chris Lattner5261d0c2009-03-28 19:18:32 +0000563 return DeclPtrTy::make(NewTemplate);
Douglas Gregord406b032009-02-06 22:42:48 +0000564}
565
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000566/// \brief Checks the validity of a template parameter list, possibly
567/// considering the template parameter list from a previous
568/// declaration.
569///
570/// If an "old" template parameter list is provided, it must be
571/// equivalent (per TemplateParameterListsAreEqual) to the "new"
572/// template parameter list.
573///
574/// \param NewParams Template parameter list for a new template
575/// declaration. This template parameter list will be updated with any
576/// default arguments that are carried through from the previous
577/// template parameter list.
578///
579/// \param OldParams If provided, template parameter list from a
580/// previous declaration of the same template. Default template
581/// arguments will be merged from the old template parameter list to
582/// the new template parameter list.
583///
584/// \returns true if an error occurred, false otherwise.
585bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
586 TemplateParameterList *OldParams) {
587 bool Invalid = false;
588
589 // C++ [temp.param]p10:
590 // The set of default template-arguments available for use with a
591 // template declaration or definition is obtained by merging the
592 // default arguments from the definition (if in scope) and all
593 // declarations in scope in the same way default function
594 // arguments are (8.3.6).
595 bool SawDefaultArgument = false;
596 SourceLocation PreviousDefaultArgLoc;
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000597
Anders Carlssonb1929502009-06-12 23:20:15 +0000598 bool SawParameterPack = false;
599 SourceLocation ParameterPackLoc;
600
Mike Stumpe0b7e032009-02-11 23:03:27 +0000601 // Dummy initialization to avoid warnings.
Douglas Gregorc5363f42009-02-11 20:46:19 +0000602 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000603 if (OldParams)
604 OldParam = OldParams->begin();
605
606 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
607 NewParamEnd = NewParams->end();
608 NewParam != NewParamEnd; ++NewParam) {
609 // Variables used to diagnose redundant default arguments
610 bool RedundantDefaultArg = false;
611 SourceLocation OldDefaultLoc;
612 SourceLocation NewDefaultLoc;
613
614 // Variables used to diagnose missing default arguments
615 bool MissingDefaultArg = false;
616
Anders Carlssonb1929502009-06-12 23:20:15 +0000617 // C++0x [temp.param]p11:
618 // If a template parameter of a class template is a template parameter pack,
619 // it must be the last template parameter.
620 if (SawParameterPack) {
621 Diag(ParameterPackLoc,
622 diag::err_template_param_pack_must_be_last_template_parameter);
623 Invalid = true;
624 }
625
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000626 // Merge default arguments for template type parameters.
627 if (TemplateTypeParmDecl *NewTypeParm
628 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
629 TemplateTypeParmDecl *OldTypeParm
630 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
631
Anders Carlssonb1929502009-06-12 23:20:15 +0000632 if (NewTypeParm->isParameterPack()) {
633 assert(!NewTypeParm->hasDefaultArgument() &&
634 "Parameter packs can't have a default argument!");
635 SawParameterPack = true;
636 ParameterPackLoc = NewTypeParm->getLocation();
637 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000638 NewTypeParm->hasDefaultArgument()) {
639 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
640 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
641 SawDefaultArgument = true;
642 RedundantDefaultArg = true;
643 PreviousDefaultArgLoc = NewDefaultLoc;
644 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
645 // Merge the default argument from the old declaration to the
646 // new declaration.
647 SawDefaultArgument = true;
648 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgument(),
649 OldTypeParm->getDefaultArgumentLoc(),
650 true);
651 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
652 } else if (NewTypeParm->hasDefaultArgument()) {
653 SawDefaultArgument = true;
654 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
655 } else if (SawDefaultArgument)
656 MissingDefaultArg = true;
657 }
658 // Merge default arguments for non-type template parameters
659 else if (NonTypeTemplateParmDecl *NewNonTypeParm
660 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
661 NonTypeTemplateParmDecl *OldNonTypeParm
662 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
663 if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
664 NewNonTypeParm->hasDefaultArgument()) {
665 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
666 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
667 SawDefaultArgument = true;
668 RedundantDefaultArg = true;
669 PreviousDefaultArgLoc = NewDefaultLoc;
670 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
671 // Merge the default argument from the old declaration to the
672 // new declaration.
673 SawDefaultArgument = true;
674 // FIXME: We need to create a new kind of "default argument"
675 // expression that points to a previous template template
676 // parameter.
677 NewNonTypeParm->setDefaultArgument(
678 OldNonTypeParm->getDefaultArgument());
679 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
680 } else if (NewNonTypeParm->hasDefaultArgument()) {
681 SawDefaultArgument = true;
682 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
683 } else if (SawDefaultArgument)
684 MissingDefaultArg = true;
685 }
686 // Merge default arguments for template template parameters
687 else {
688 TemplateTemplateParmDecl *NewTemplateParm
689 = cast<TemplateTemplateParmDecl>(*NewParam);
690 TemplateTemplateParmDecl *OldTemplateParm
691 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
692 if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
693 NewTemplateParm->hasDefaultArgument()) {
694 OldDefaultLoc = OldTemplateParm->getDefaultArgumentLoc();
695 NewDefaultLoc = NewTemplateParm->getDefaultArgumentLoc();
696 SawDefaultArgument = true;
697 RedundantDefaultArg = true;
698 PreviousDefaultArgLoc = NewDefaultLoc;
699 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
700 // Merge the default argument from the old declaration to the
701 // new declaration.
702 SawDefaultArgument = true;
Mike Stumpe127ae32009-05-16 07:39:55 +0000703 // FIXME: We need to create a new kind of "default argument" expression
704 // that points to a previous template template parameter.
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000705 NewTemplateParm->setDefaultArgument(
706 OldTemplateParm->getDefaultArgument());
707 PreviousDefaultArgLoc = OldTemplateParm->getDefaultArgumentLoc();
708 } else if (NewTemplateParm->hasDefaultArgument()) {
709 SawDefaultArgument = true;
710 PreviousDefaultArgLoc = NewTemplateParm->getDefaultArgumentLoc();
711 } else if (SawDefaultArgument)
712 MissingDefaultArg = true;
713 }
714
715 if (RedundantDefaultArg) {
716 // C++ [temp.param]p12:
717 // A template-parameter shall not be given default arguments
718 // by two different declarations in the same scope.
719 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
720 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
721 Invalid = true;
722 } else if (MissingDefaultArg) {
723 // C++ [temp.param]p11:
724 // If a template-parameter has a default template-argument,
725 // all subsequent template-parameters shall have a default
726 // template-argument supplied.
727 Diag((*NewParam)->getLocation(),
728 diag::err_template_param_default_arg_missing);
729 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
730 Invalid = true;
731 }
732
733 // If we have an old template parameter list that we're merging
734 // in, move on to the next parameter.
735 if (OldParams)
736 ++OldParam;
737 }
738
739 return Invalid;
740}
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000741
Douglas Gregorb462c322009-07-21 23:53:31 +0000742/// \brief Match the given template parameter lists to the given scope
743/// specifier, returning the template parameter list that applies to the
744/// name.
745///
746/// \param DeclStartLoc the start of the declaration that has a scope
747/// specifier or a template parameter list.
748///
749/// \param SS the scope specifier that will be matched to the given template
750/// parameter lists. This scope specifier precedes a qualified name that is
751/// being declared.
752///
753/// \param ParamLists the template parameter lists, from the outermost to the
754/// innermost template parameter lists.
755///
756/// \param NumParamLists the number of template parameter lists in ParamLists.
757///
758/// \returns the template parameter list, if any, that corresponds to the
759/// name that is preceded by the scope specifier @p SS. This template
760/// parameter list may be have template parameters (if we're declaring a
761/// template) or may have no template parameters (if we're declaring a
762/// template specialization), or may be NULL (if we were's declaring isn't
763/// itself a template).
764TemplateParameterList *
765Sema::MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc,
766 const CXXScopeSpec &SS,
767 TemplateParameterList **ParamLists,
768 unsigned NumParamLists) {
769 // FIXME: This routine will need a lot more testing once we have support for
770 // member templates.
771
772 // Find the template-ids that occur within the nested-name-specifier. These
773 // template-ids will match up with the template parameter lists.
774 llvm::SmallVector<const TemplateSpecializationType *, 4>
775 TemplateIdsInSpecifier;
776 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
777 NNS; NNS = NNS->getPrefix()) {
778 if (const TemplateSpecializationType *SpecType
779 = dyn_cast_or_null<TemplateSpecializationType>(NNS->getAsType())) {
780 TemplateDecl *Template = SpecType->getTemplateName().getAsTemplateDecl();
781 if (!Template)
782 continue; // FIXME: should this be an error? probably...
783
784 if (const RecordType *Record = SpecType->getAsRecordType()) {
785 ClassTemplateSpecializationDecl *SpecDecl
786 = cast<ClassTemplateSpecializationDecl>(Record->getDecl());
787 // If the nested name specifier refers to an explicit specialization,
788 // we don't need a template<> header.
789 if (SpecDecl->getSpecializationKind() == TSK_ExplicitSpecialization)
790 continue;
791 }
792
793 TemplateIdsInSpecifier.push_back(SpecType);
794 }
795 }
796
797 // Reverse the list of template-ids in the scope specifier, so that we can
798 // more easily match up the template-ids and the template parameter lists.
799 std::reverse(TemplateIdsInSpecifier.begin(), TemplateIdsInSpecifier.end());
800
801 SourceLocation FirstTemplateLoc = DeclStartLoc;
802 if (NumParamLists)
803 FirstTemplateLoc = ParamLists[0]->getTemplateLoc();
804
805 // Match the template-ids found in the specifier to the template parameter
806 // lists.
807 unsigned Idx = 0;
808 for (unsigned NumTemplateIds = TemplateIdsInSpecifier.size();
809 Idx != NumTemplateIds; ++Idx) {
810 bool DependentTemplateId = TemplateIdsInSpecifier[Idx]->isDependentType();
811 if (Idx >= NumParamLists) {
812 // We have a template-id without a corresponding template parameter
813 // list.
814 if (DependentTemplateId) {
815 // FIXME: the location information here isn't great.
816 Diag(SS.getRange().getBegin(),
817 diag::err_template_spec_needs_template_parameters)
818 << QualType(TemplateIdsInSpecifier[Idx], 0)
819 << SS.getRange();
820 } else {
821 Diag(SS.getRange().getBegin(), diag::err_template_spec_needs_header)
822 << SS.getRange()
823 << CodeModificationHint::CreateInsertion(FirstTemplateLoc,
824 "template<> ");
825 }
826 return 0;
827 }
828
829 // Check the template parameter list against its corresponding template-id.
830 TemplateDecl *Template
831 = TemplateIdsInSpecifier[Idx]->getTemplateName().getAsTemplateDecl();
832 TemplateParameterListsAreEqual(ParamLists[Idx],
833 Template->getTemplateParameters(),
834 true);
835 }
836
837 // If there were at least as many template-ids as there were template
838 // parameter lists, then there are no template parameter lists remaining for
839 // the declaration itself.
840 if (Idx >= NumParamLists)
841 return 0;
842
843 // If there were too many template parameter lists, complain about that now.
844 if (Idx != NumParamLists - 1) {
845 while (Idx < NumParamLists - 1) {
846 Diag(ParamLists[Idx]->getTemplateLoc(),
847 diag::err_template_spec_extra_headers)
848 << SourceRange(ParamLists[Idx]->getTemplateLoc(),
849 ParamLists[Idx]->getRAngleLoc());
850 ++Idx;
851 }
852 }
853
854 // Return the last template parameter list, which corresponds to the
855 // entity being declared.
856 return ParamLists[NumParamLists - 1];
857}
858
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000859/// \brief Translates template arguments as provided by the parser
860/// into template arguments used by semantic analysis.
861static void
862translateTemplateArguments(ASTTemplateArgsPtr &TemplateArgsIn,
863 SourceLocation *TemplateArgLocs,
864 llvm::SmallVector<TemplateArgument, 16> &TemplateArgs) {
865 TemplateArgs.reserve(TemplateArgsIn.size());
866
867 void **Args = TemplateArgsIn.getArgs();
868 bool *ArgIsType = TemplateArgsIn.getArgIsType();
869 for (unsigned Arg = 0, Last = TemplateArgsIn.size(); Arg != Last; ++Arg) {
870 TemplateArgs.push_back(
871 ArgIsType[Arg]? TemplateArgument(TemplateArgLocs[Arg],
872 QualType::getFromOpaquePtr(Args[Arg]))
873 : TemplateArgument(reinterpret_cast<Expr *>(Args[Arg])));
874 }
875}
876
Douglas Gregordd13e842009-03-30 22:58:21 +0000877QualType Sema::CheckTemplateIdType(TemplateName Name,
878 SourceLocation TemplateLoc,
879 SourceLocation LAngleLoc,
880 const TemplateArgument *TemplateArgs,
881 unsigned NumTemplateArgs,
882 SourceLocation RAngleLoc) {
883 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregoraabb8502009-03-31 00:43:58 +0000884 if (!Template) {
885 // The template name does not resolve to a template, so we just
886 // build a dependent template-id type.
Douglas Gregoraabb8502009-03-31 00:43:58 +0000887 return Context.getTemplateSpecializationType(Name, TemplateArgs,
Douglas Gregor4262bc92009-07-28 23:00:59 +0000888 NumTemplateArgs);
Douglas Gregoraabb8502009-03-31 00:43:58 +0000889 }
Douglas Gregordd13e842009-03-30 22:58:21 +0000890
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000891 // Check that the template argument list is well-formed for this
892 // template.
Anders Carlssonb0fc9992009-06-23 01:26:57 +0000893 TemplateArgumentListBuilder Converted(Template->getTemplateParameters(),
894 NumTemplateArgs);
Douglas Gregordd13e842009-03-30 22:58:21 +0000895 if (CheckTemplateArgumentList(Template, TemplateLoc, LAngleLoc,
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000896 TemplateArgs, NumTemplateArgs, RAngleLoc,
Douglas Gregorecd63b82009-07-01 00:28:38 +0000897 false, Converted))
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000898 return QualType();
899
Anders Carlssonb0fc9992009-06-23 01:26:57 +0000900 assert((Converted.structuredSize() ==
Douglas Gregordd13e842009-03-30 22:58:21 +0000901 Template->getTemplateParameters()->size()) &&
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000902 "Converted template argument list is too short!");
903
904 QualType CanonType;
905
Douglas Gregordd13e842009-03-30 22:58:21 +0000906 if (TemplateSpecializationType::anyDependentTemplateArguments(
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000907 TemplateArgs,
908 NumTemplateArgs)) {
909 // This class template specialization is a dependent
910 // type. Therefore, its canonical type is another class template
911 // specialization type that contains all of the converted
912 // arguments in canonical form. This ensures that, e.g., A<T> and
913 // A<T, T> have identical types when A is declared as:
914 //
915 // template<typename T, typename U = T> struct A;
Douglas Gregorb88ba412009-05-07 06:41:52 +0000916 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
917 CanonType = Context.getTemplateSpecializationType(CanonName,
Anders Carlssonb0fc9992009-06-23 01:26:57 +0000918 Converted.getFlatArguments(),
919 Converted.flatSize());
Douglas Gregor4262bc92009-07-28 23:00:59 +0000920
921 // FIXME: CanonType is not actually the canonical type, and unfortunately
922 // it is a TemplateTypeSpecializationType that we will never use again.
923 // In the future, we need to teach getTemplateSpecializationType to only
924 // build the canonical type and return that to us.
925 CanonType = Context.getCanonicalType(CanonType);
Douglas Gregordd13e842009-03-30 22:58:21 +0000926 } else if (ClassTemplateDecl *ClassTemplate
927 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000928 // Find the class template specialization declaration that
929 // corresponds to these arguments.
930 llvm::FoldingSetNodeID ID;
Anders Carlssona35faf92009-06-05 03:43:12 +0000931 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlssonb0fc9992009-06-23 01:26:57 +0000932 Converted.getFlatArguments(),
933 Converted.flatSize());
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000934 void *InsertPos = 0;
935 ClassTemplateSpecializationDecl *Decl
936 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
937 if (!Decl) {
938 // This is the first time we have referenced this class template
939 // specialization. Create the canonical declaration and add it to
940 // the set of specializations.
941 Decl = ClassTemplateSpecializationDecl::Create(Context,
Anders Carlssona35faf92009-06-05 03:43:12 +0000942 ClassTemplate->getDeclContext(),
943 TemplateLoc,
944 ClassTemplate,
Anders Carlssonb0fc9992009-06-23 01:26:57 +0000945 Converted, 0);
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000946 ClassTemplate->getSpecializations().InsertNode(Decl, InsertPos);
947 Decl->setLexicalDeclContext(CurContext);
948 }
949
950 CanonType = Context.getTypeDeclType(Decl);
951 }
952
953 // Build the fully-sugared type for this class template
954 // specialization, which refers back to the class template
955 // specialization we created or found.
Douglas Gregordd13e842009-03-30 22:58:21 +0000956 return Context.getTemplateSpecializationType(Name, TemplateArgs,
957 NumTemplateArgs, CanonType);
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000958}
959
Douglas Gregora08b6c72009-02-17 23:15:12 +0000960Action::TypeResult
Douglas Gregordd13e842009-03-30 22:58:21 +0000961Sema::ActOnTemplateIdType(TemplateTy TemplateD, SourceLocation TemplateLoc,
962 SourceLocation LAngleLoc,
963 ASTTemplateArgsPtr TemplateArgsIn,
964 SourceLocation *TemplateArgLocs,
965 SourceLocation RAngleLoc) {
966 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Douglas Gregor8e458f42009-02-09 18:46:07 +0000967
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000968 // Translate the parser's template argument list in our AST format.
969 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
970 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000971
Douglas Gregordd13e842009-03-30 22:58:21 +0000972 QualType Result = CheckTemplateIdType(Template, TemplateLoc, LAngleLoc,
Jay Foad9e6bef42009-05-21 09:52:38 +0000973 TemplateArgs.data(),
974 TemplateArgs.size(),
Douglas Gregordd13e842009-03-30 22:58:21 +0000975 RAngleLoc);
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000976 TemplateArgsIn.release();
Douglas Gregord7cb0372009-04-01 21:51:26 +0000977
978 if (Result.isNull())
979 return true;
980
Douglas Gregor6f37b582009-02-09 19:34:22 +0000981 return Result.getAsOpaquePtr();
Douglas Gregor8e458f42009-02-09 18:46:07 +0000982}
983
Douglas Gregor28857752009-06-30 22:34:41 +0000984Sema::OwningExprResult Sema::BuildTemplateIdExpr(TemplateName Template,
985 SourceLocation TemplateNameLoc,
986 SourceLocation LAngleLoc,
987 const TemplateArgument *TemplateArgs,
988 unsigned NumTemplateArgs,
989 SourceLocation RAngleLoc) {
990 // FIXME: Can we do any checking at this point? I guess we could check the
991 // template arguments that we have against the template name, if the template
992 // name refers to a single template. That's not a terribly common case,
993 // though.
994 return Owned(TemplateIdRefExpr::Create(Context,
995 /*FIXME: New type?*/Context.OverloadTy,
996 /*FIXME: Necessary?*/0,
997 /*FIXME: Necessary?*/SourceRange(),
998 Template, TemplateNameLoc, LAngleLoc,
999 TemplateArgs,
1000 NumTemplateArgs, RAngleLoc));
1001}
1002
1003Sema::OwningExprResult Sema::ActOnTemplateIdExpr(TemplateTy TemplateD,
1004 SourceLocation TemplateNameLoc,
1005 SourceLocation LAngleLoc,
1006 ASTTemplateArgsPtr TemplateArgsIn,
1007 SourceLocation *TemplateArgLocs,
1008 SourceLocation RAngleLoc) {
1009 TemplateName Template = TemplateD.getAsVal<TemplateName>();
1010
1011 // Translate the parser's template argument list in our AST format.
1012 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
1013 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
Douglas Gregorf2fedc62009-07-22 20:55:49 +00001014 TemplateArgsIn.release();
Douglas Gregor28857752009-06-30 22:34:41 +00001015
1016 return BuildTemplateIdExpr(Template, TemplateNameLoc, LAngleLoc,
1017 TemplateArgs.data(), TemplateArgs.size(),
1018 RAngleLoc);
1019}
1020
Douglas Gregoraabb8502009-03-31 00:43:58 +00001021/// \brief Form a dependent template name.
1022///
1023/// This action forms a dependent template name given the template
1024/// name and its (presumably dependent) scope specifier. For
1025/// example, given "MetaFun::template apply", the scope specifier \p
1026/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
1027/// of the "template" keyword, and "apply" is the \p Name.
1028Sema::TemplateTy
1029Sema::ActOnDependentTemplateName(SourceLocation TemplateKWLoc,
1030 const IdentifierInfo &Name,
1031 SourceLocation NameLoc,
1032 const CXXScopeSpec &SS) {
1033 if (!SS.isSet() || SS.isInvalid())
1034 return TemplateTy();
1035
1036 NestedNameSpecifier *Qualifier
1037 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
1038
1039 // FIXME: member of the current instantiation
1040
1041 if (!Qualifier->isDependent()) {
1042 // C++0x [temp.names]p5:
1043 // If a name prefixed by the keyword template is not the name of
1044 // a template, the program is ill-formed. [Note: the keyword
1045 // template may not be applied to non-template members of class
1046 // templates. -end note ] [ Note: as is the case with the
1047 // typename prefix, the template prefix is allowed in cases
1048 // where it is not strictly necessary; i.e., when the
1049 // nested-name-specifier or the expression on the left of the ->
1050 // or . is not dependent on a template-parameter, or the use
1051 // does not appear in the scope of a template. -end note]
1052 //
1053 // Note: C++03 was more strict here, because it banned the use of
1054 // the "template" keyword prior to a template-name that was not a
1055 // dependent name. C++ DR468 relaxed this requirement (the
1056 // "template" keyword is now permitted). We follow the C++0x
1057 // rules, even in C++03 mode, retroactively applying the DR.
1058 TemplateTy Template;
1059 TemplateNameKind TNK = isTemplateName(Name, 0, Template, &SS);
1060 if (TNK == TNK_Non_template) {
1061 Diag(NameLoc, diag::err_template_kw_refers_to_non_template)
1062 << &Name;
1063 return TemplateTy();
1064 }
1065
1066 return Template;
1067 }
1068
1069 return TemplateTy::make(Context.getDependentTemplateName(Qualifier, &Name));
1070}
1071
Anders Carlssonfdd33cc2009-06-13 00:33:33 +00001072bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
1073 const TemplateArgument &Arg,
1074 TemplateArgumentListBuilder &Converted) {
1075 // Check template type parameter.
1076 if (Arg.getKind() != TemplateArgument::Type) {
1077 // C++ [temp.arg.type]p1:
1078 // A template-argument for a template-parameter which is a
1079 // type shall be a type-id.
1080
1081 // We have a template type parameter but the template argument
1082 // is not a type.
1083 Diag(Arg.getLocation(), diag::err_template_arg_must_be_type);
1084 Diag(Param->getLocation(), diag::note_template_param_here);
1085
1086 return true;
1087 }
1088
1089 if (CheckTemplateArgument(Param, Arg.getAsType(), Arg.getLocation()))
1090 return true;
1091
1092 // Add the converted template type argument.
Anders Carlssonb0fc9992009-06-23 01:26:57 +00001093 Converted.Append(
Anders Carlssonfdd33cc2009-06-13 00:33:33 +00001094 TemplateArgument(Arg.getLocation(),
1095 Context.getCanonicalType(Arg.getAsType())));
1096 return false;
1097}
1098
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001099/// \brief Check that the given template argument list is well-formed
1100/// for specializing the given template.
1101bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
1102 SourceLocation TemplateLoc,
1103 SourceLocation LAngleLoc,
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001104 const TemplateArgument *TemplateArgs,
1105 unsigned NumTemplateArgs,
Douglas Gregorad964b32009-02-17 01:05:43 +00001106 SourceLocation RAngleLoc,
Douglas Gregorecd63b82009-07-01 00:28:38 +00001107 bool PartialTemplateArgs,
Anders Carlssona35faf92009-06-05 03:43:12 +00001108 TemplateArgumentListBuilder &Converted) {
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001109 TemplateParameterList *Params = Template->getTemplateParameters();
1110 unsigned NumParams = Params->size();
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001111 unsigned NumArgs = NumTemplateArgs;
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001112 bool Invalid = false;
1113
Anders Carlsson4ffb5812009-06-13 02:08:00 +00001114 bool HasParameterPack =
1115 NumParams > 0 && Params->getParam(NumParams - 1)->isTemplateParameterPack();
1116
1117 if ((NumArgs > NumParams && !HasParameterPack) ||
Douglas Gregorecd63b82009-07-01 00:28:38 +00001118 (NumArgs < Params->getMinRequiredArguments() &&
1119 !PartialTemplateArgs)) {
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001120 // FIXME: point at either the first arg beyond what we can handle,
1121 // or the '>', depending on whether we have too many or too few
1122 // arguments.
1123 SourceRange Range;
1124 if (NumArgs > NumParams)
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001125 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001126 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
1127 << (NumArgs > NumParams)
1128 << (isa<ClassTemplateDecl>(Template)? 0 :
1129 isa<FunctionTemplateDecl>(Template)? 1 :
1130 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
1131 << Template << Range;
Douglas Gregorc347d8e2009-02-11 18:16:40 +00001132 Diag(Template->getLocation(), diag::note_template_decl_here)
1133 << Params->getSourceRange();
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001134 Invalid = true;
1135 }
1136
1137 // C++ [temp.arg]p1:
1138 // [...] The type and form of each template-argument specified in
1139 // a template-id shall match the type and form specified for the
1140 // corresponding parameter declared by the template in its
1141 // template-parameter-list.
1142 unsigned ArgIdx = 0;
1143 for (TemplateParameterList::iterator Param = Params->begin(),
1144 ParamEnd = Params->end();
1145 Param != ParamEnd; ++Param, ++ArgIdx) {
Douglas Gregorecd63b82009-07-01 00:28:38 +00001146 if (ArgIdx > NumArgs && PartialTemplateArgs)
1147 break;
1148
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001149 // Decode the template argument
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001150 TemplateArgument Arg;
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001151 if (ArgIdx >= NumArgs) {
Douglas Gregorad964b32009-02-17 01:05:43 +00001152 // Retrieve the default template argument from the template
1153 // parameter.
1154 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
Anders Carlsson4ffb5812009-06-13 02:08:00 +00001155 if (TTP->isParameterPack()) {
Anders Carlssonb0fc9992009-06-23 01:26:57 +00001156 // We have an empty argument pack.
1157 Converted.BeginPack();
1158 Converted.EndPack();
Anders Carlsson4ffb5812009-06-13 02:08:00 +00001159 break;
1160 }
1161
Douglas Gregorad964b32009-02-17 01:05:43 +00001162 if (!TTP->hasDefaultArgument())
1163 break;
1164
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001165 QualType ArgType = TTP->getDefaultArgument();
Douglas Gregor74296542009-02-27 19:31:52 +00001166
1167 // If the argument type is dependent, instantiate it now based
1168 // on the previously-computed template arguments.
Douglas Gregor56d25a72009-03-10 20:44:00 +00001169 if (ArgType->isDependentType()) {
1170 InstantiatingTemplate Inst(*this, TemplateLoc,
Anders Carlssonb0fc9992009-06-23 01:26:57 +00001171 Template, Converted.getFlatArguments(),
Anders Carlssona35faf92009-06-05 03:43:12 +00001172 Converted.flatSize(),
Douglas Gregor56d25a72009-03-10 20:44:00 +00001173 SourceRange(TemplateLoc, RAngleLoc));
Douglas Gregorf9e7d3d2009-05-11 23:53:27 +00001174
Anders Carlsson0233eb62009-06-05 04:47:51 +00001175 TemplateArgumentList TemplateArgs(Context, Converted,
Anders Carlssonb0fc9992009-06-23 01:26:57 +00001176 /*TakeArgs=*/false);
Douglas Gregorf9e7d3d2009-05-11 23:53:27 +00001177 ArgType = InstantiateType(ArgType, TemplateArgs,
Douglas Gregor74296542009-02-27 19:31:52 +00001178 TTP->getDefaultArgumentLoc(),
1179 TTP->getDeclName());
Douglas Gregor56d25a72009-03-10 20:44:00 +00001180 }
Douglas Gregor74296542009-02-27 19:31:52 +00001181
1182 if (ArgType.isNull())
Douglas Gregorf57dcd02009-02-28 00:25:32 +00001183 return true;
Douglas Gregor74296542009-02-27 19:31:52 +00001184
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001185 Arg = TemplateArgument(TTP->getLocation(), ArgType);
Douglas Gregorad964b32009-02-17 01:05:43 +00001186 } else if (NonTypeTemplateParmDecl *NTTP
1187 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
1188 if (!NTTP->hasDefaultArgument())
1189 break;
1190
Anders Carlsson0297caf2009-06-11 16:06:49 +00001191 InstantiatingTemplate Inst(*this, TemplateLoc,
Anders Carlssonb0fc9992009-06-23 01:26:57 +00001192 Template, Converted.getFlatArguments(),
Anders Carlsson0297caf2009-06-11 16:06:49 +00001193 Converted.flatSize(),
1194 SourceRange(TemplateLoc, RAngleLoc));
1195
1196 TemplateArgumentList TemplateArgs(Context, Converted,
Anders Carlssonb0fc9992009-06-23 01:26:57 +00001197 /*TakeArgs=*/false);
Anders Carlsson0297caf2009-06-11 16:06:49 +00001198
1199 Sema::OwningExprResult E = InstantiateExpr(NTTP->getDefaultArgument(),
1200 TemplateArgs);
1201 if (E.isInvalid())
1202 return true;
1203
1204 Arg = TemplateArgument(E.takeAs<Expr>());
Douglas Gregorad964b32009-02-17 01:05:43 +00001205 } else {
1206 TemplateTemplateParmDecl *TempParm
1207 = cast<TemplateTemplateParmDecl>(*Param);
1208
1209 if (!TempParm->hasDefaultArgument())
1210 break;
1211
Douglas Gregored3a3982009-03-03 04:44:36 +00001212 // FIXME: Instantiate default argument
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001213 Arg = TemplateArgument(TempParm->getDefaultArgument());
Douglas Gregorad964b32009-02-17 01:05:43 +00001214 }
1215 } else {
1216 // Retrieve the template argument produced by the user.
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001217 Arg = TemplateArgs[ArgIdx];
Douglas Gregorad964b32009-02-17 01:05:43 +00001218 }
1219
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001220
1221 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
Anders Carlsson4ffb5812009-06-13 02:08:00 +00001222 if (TTP->isParameterPack()) {
Anders Carlssonb0fc9992009-06-23 01:26:57 +00001223 Converted.BeginPack();
Anders Carlsson4ffb5812009-06-13 02:08:00 +00001224 // Check all the remaining arguments (if any).
1225 for (; ArgIdx < NumArgs; ++ArgIdx) {
1226 if (CheckTemplateTypeArgument(TTP, TemplateArgs[ArgIdx], Converted))
1227 Invalid = true;
1228 }
1229
Anders Carlssonb0fc9992009-06-23 01:26:57 +00001230 Converted.EndPack();
Anders Carlsson4ffb5812009-06-13 02:08:00 +00001231 } else {
1232 if (CheckTemplateTypeArgument(TTP, Arg, Converted))
1233 Invalid = true;
1234 }
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001235 } else if (NonTypeTemplateParmDecl *NTTP
1236 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
1237 // Check non-type template parameters.
Douglas Gregored3a3982009-03-03 04:44:36 +00001238
1239 // Instantiate the type of the non-type template parameter with
1240 // the template arguments we've seen thus far.
1241 QualType NTTPType = NTTP->getType();
1242 if (NTTPType->isDependentType()) {
1243 // Instantiate the type of the non-type template parameter.
Douglas Gregor56d25a72009-03-10 20:44:00 +00001244 InstantiatingTemplate Inst(*this, TemplateLoc,
Anders Carlssonb0fc9992009-06-23 01:26:57 +00001245 Template, Converted.getFlatArguments(),
Anders Carlssona35faf92009-06-05 03:43:12 +00001246 Converted.flatSize(),
Douglas Gregor56d25a72009-03-10 20:44:00 +00001247 SourceRange(TemplateLoc, RAngleLoc));
1248
Anders Carlsson0233eb62009-06-05 04:47:51 +00001249 TemplateArgumentList TemplateArgs(Context, Converted,
Anders Carlssonb0fc9992009-06-23 01:26:57 +00001250 /*TakeArgs=*/false);
Douglas Gregorf9e7d3d2009-05-11 23:53:27 +00001251 NTTPType = InstantiateType(NTTPType, TemplateArgs,
Douglas Gregored3a3982009-03-03 04:44:36 +00001252 NTTP->getLocation(),
1253 NTTP->getDeclName());
1254 // If that worked, check the non-type template parameter type
1255 // for validity.
1256 if (!NTTPType.isNull())
1257 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
1258 NTTP->getLocation());
Douglas Gregored3a3982009-03-03 04:44:36 +00001259 if (NTTPType.isNull()) {
1260 Invalid = true;
1261 break;
1262 }
1263 }
1264
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001265 switch (Arg.getKind()) {
Douglas Gregorbf23a8a2009-06-04 00:03:07 +00001266 case TemplateArgument::Null:
1267 assert(false && "Should never see a NULL template argument here");
1268 break;
1269
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001270 case TemplateArgument::Expression: {
1271 Expr *E = Arg.getAsExpr();
Douglas Gregor8f378a92009-06-11 18:10:32 +00001272 TemplateArgument Result;
1273 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001274 Invalid = true;
Douglas Gregor8f378a92009-06-11 18:10:32 +00001275 else
Anders Carlssonb0fc9992009-06-23 01:26:57 +00001276 Converted.Append(Result);
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001277 break;
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001278 }
1279
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001280 case TemplateArgument::Declaration:
1281 case TemplateArgument::Integral:
1282 // We've already checked this template argument, so just copy
1283 // it to the list of converted arguments.
Anders Carlssonb0fc9992009-06-23 01:26:57 +00001284 Converted.Append(Arg);
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001285 break;
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001286
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001287 case TemplateArgument::Type:
1288 // We have a non-type template parameter but the template
1289 // argument is a type.
1290
1291 // C++ [temp.arg]p2:
1292 // In a template-argument, an ambiguity between a type-id and
1293 // an expression is resolved to a type-id, regardless of the
1294 // form of the corresponding template-parameter.
1295 //
1296 // We warn specifically about this case, since it can be rather
1297 // confusing for users.
1298 if (Arg.getAsType()->isFunctionType())
1299 Diag(Arg.getLocation(), diag::err_template_arg_nontype_ambig)
1300 << Arg.getAsType();
1301 else
1302 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr);
1303 Diag((*Param)->getLocation(), diag::note_template_param_here);
1304 Invalid = true;
Anders Carlsson584b5062009-06-15 17:04:53 +00001305 break;
1306
1307 case TemplateArgument::Pack:
1308 assert(0 && "FIXME: Implement!");
1309 break;
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001310 }
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001311 } else {
1312 // Check template template parameters.
1313 TemplateTemplateParmDecl *TempParm
1314 = cast<TemplateTemplateParmDecl>(*Param);
1315
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001316 switch (Arg.getKind()) {
Douglas Gregorbf23a8a2009-06-04 00:03:07 +00001317 case TemplateArgument::Null:
1318 assert(false && "Should never see a NULL template argument here");
1319 break;
1320
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001321 case TemplateArgument::Expression: {
1322 Expr *ArgExpr = Arg.getAsExpr();
1323 if (ArgExpr && isa<DeclRefExpr>(ArgExpr) &&
1324 isa<TemplateDecl>(cast<DeclRefExpr>(ArgExpr)->getDecl())) {
1325 if (CheckTemplateArgument(TempParm, cast<DeclRefExpr>(ArgExpr)))
1326 Invalid = true;
1327
1328 // Add the converted template argument.
Douglas Gregor9054f982009-05-10 22:57:19 +00001329 Decl *D
Argiris Kirtzidis17c7cab2009-07-18 00:34:25 +00001330 = cast<DeclRefExpr>(ArgExpr)->getDecl()->getCanonicalDecl();
Anders Carlssonb0fc9992009-06-23 01:26:57 +00001331 Converted.Append(TemplateArgument(Arg.getLocation(), D));
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001332 continue;
1333 }
1334 }
1335 // fall through
1336
1337 case TemplateArgument::Type: {
1338 // We have a template template parameter but the template
1339 // argument does not refer to a template.
1340 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
1341 Invalid = true;
1342 break;
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001343 }
1344
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001345 case TemplateArgument::Declaration:
1346 // We've already checked this template argument, so just copy
1347 // it to the list of converted arguments.
Anders Carlssonb0fc9992009-06-23 01:26:57 +00001348 Converted.Append(Arg);
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001349 break;
1350
1351 case TemplateArgument::Integral:
1352 assert(false && "Integral argument with template template parameter");
1353 break;
Anders Carlsson584b5062009-06-15 17:04:53 +00001354
1355 case TemplateArgument::Pack:
1356 assert(0 && "FIXME: Implement!");
1357 break;
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001358 }
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001359 }
1360 }
1361
1362 return Invalid;
1363}
1364
1365/// \brief Check a template argument against its corresponding
1366/// template type parameter.
1367///
1368/// This routine implements the semantics of C++ [temp.arg.type]. It
1369/// returns true if an error occurred, and false otherwise.
1370bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
1371 QualType Arg, SourceLocation ArgLoc) {
1372 // C++ [temp.arg.type]p2:
1373 // A local type, a type with no linkage, an unnamed type or a type
1374 // compounded from any of these types shall not be used as a
1375 // template-argument for a template type-parameter.
1376 //
1377 // FIXME: Perform the recursive and no-linkage type checks.
1378 const TagType *Tag = 0;
1379 if (const EnumType *EnumT = Arg->getAsEnumType())
1380 Tag = EnumT;
Ted Kremenekd9b39bf2009-07-17 17:50:17 +00001381 else if (const RecordType *RecordT = Arg->getAsRecordType())
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001382 Tag = RecordT;
1383 if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod())
1384 return Diag(ArgLoc, diag::err_template_arg_local_type)
1385 << QualType(Tag, 0);
Douglas Gregor04385782009-03-10 18:33:27 +00001386 else if (Tag && !Tag->getDecl()->getDeclName() &&
1387 !Tag->getDecl()->getTypedefForAnonDecl()) {
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001388 Diag(ArgLoc, diag::err_template_arg_unnamed_type);
1389 Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here);
1390 return true;
1391 }
1392
1393 return false;
1394}
1395
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001396/// \brief Checks whether the given template argument is the address
1397/// of an object or function according to C++ [temp.arg.nontype]p1.
Douglas Gregorad964b32009-02-17 01:05:43 +00001398bool Sema::CheckTemplateArgumentAddressOfObjectOrFunction(Expr *Arg,
1399 NamedDecl *&Entity) {
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001400 bool Invalid = false;
1401
1402 // See through any implicit casts we added to fix the type.
1403 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
1404 Arg = Cast->getSubExpr();
1405
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001406 // C++0x allows nullptr, and there's no further checking to be done for that.
1407 if (Arg->getType()->isNullPtrType())
1408 return false;
1409
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001410 // C++ [temp.arg.nontype]p1:
1411 //
1412 // A template-argument for a non-type, non-template
1413 // template-parameter shall be one of: [...]
1414 //
1415 // -- the address of an object or function with external
1416 // linkage, including function templates and function
1417 // template-ids but excluding non-static class members,
1418 // expressed as & id-expression where the & is optional if
1419 // the name refers to a function or array, or if the
1420 // corresponding template-parameter is a reference; or
1421 DeclRefExpr *DRE = 0;
1422
1423 // Ignore (and complain about) any excess parentheses.
1424 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
1425 if (!Invalid) {
1426 Diag(Arg->getSourceRange().getBegin(),
1427 diag::err_template_arg_extra_parens)
1428 << Arg->getSourceRange();
1429 Invalid = true;
1430 }
1431
1432 Arg = Parens->getSubExpr();
1433 }
1434
1435 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
1436 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
1437 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
1438 } else
1439 DRE = dyn_cast<DeclRefExpr>(Arg);
1440
1441 if (!DRE || !isa<ValueDecl>(DRE->getDecl()))
1442 return Diag(Arg->getSourceRange().getBegin(),
1443 diag::err_template_arg_not_object_or_func_form)
1444 << Arg->getSourceRange();
1445
1446 // Cannot refer to non-static data members
1447 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl()))
1448 return Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
1449 << Field << Arg->getSourceRange();
1450
1451 // Cannot refer to non-static member functions
1452 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
1453 if (!Method->isStatic())
1454 return Diag(Arg->getSourceRange().getBegin(),
1455 diag::err_template_arg_method)
1456 << Method << Arg->getSourceRange();
1457
1458 // Functions must have external linkage.
1459 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
1460 if (Func->getStorageClass() == FunctionDecl::Static) {
1461 Diag(Arg->getSourceRange().getBegin(),
1462 diag::err_template_arg_function_not_extern)
1463 << Func << Arg->getSourceRange();
1464 Diag(Func->getLocation(), diag::note_template_arg_internal_object)
1465 << true;
1466 return true;
1467 }
1468
1469 // Okay: we've named a function with external linkage.
Douglas Gregorad964b32009-02-17 01:05:43 +00001470 Entity = Func;
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001471 return Invalid;
1472 }
1473
1474 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
1475 if (!Var->hasGlobalStorage()) {
1476 Diag(Arg->getSourceRange().getBegin(),
1477 diag::err_template_arg_object_not_extern)
1478 << Var << Arg->getSourceRange();
1479 Diag(Var->getLocation(), diag::note_template_arg_internal_object)
1480 << true;
1481 return true;
1482 }
1483
1484 // Okay: we've named an object with external linkage
Douglas Gregorad964b32009-02-17 01:05:43 +00001485 Entity = Var;
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001486 return Invalid;
1487 }
1488
1489 // We found something else, but we don't know specifically what it is.
1490 Diag(Arg->getSourceRange().getBegin(),
1491 diag::err_template_arg_not_object_or_func)
1492 << Arg->getSourceRange();
1493 Diag(DRE->getDecl()->getLocation(),
1494 diag::note_template_arg_refers_here);
1495 return true;
1496}
1497
1498/// \brief Checks whether the given template argument is a pointer to
1499/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregorad964b32009-02-17 01:05:43 +00001500bool
1501Sema::CheckTemplateArgumentPointerToMember(Expr *Arg, NamedDecl *&Member) {
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001502 bool Invalid = false;
1503
1504 // See through any implicit casts we added to fix the type.
1505 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
1506 Arg = Cast->getSubExpr();
1507
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001508 // C++0x allows nullptr, and there's no further checking to be done for that.
1509 if (Arg->getType()->isNullPtrType())
1510 return false;
1511
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001512 // C++ [temp.arg.nontype]p1:
1513 //
1514 // A template-argument for a non-type, non-template
1515 // template-parameter shall be one of: [...]
1516 //
1517 // -- a pointer to member expressed as described in 5.3.1.
1518 QualifiedDeclRefExpr *DRE = 0;
1519
1520 // Ignore (and complain about) any excess parentheses.
1521 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
1522 if (!Invalid) {
1523 Diag(Arg->getSourceRange().getBegin(),
1524 diag::err_template_arg_extra_parens)
1525 << Arg->getSourceRange();
1526 Invalid = true;
1527 }
1528
1529 Arg = Parens->getSubExpr();
1530 }
1531
1532 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg))
1533 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
1534 DRE = dyn_cast<QualifiedDeclRefExpr>(UnOp->getSubExpr());
1535
1536 if (!DRE)
1537 return Diag(Arg->getSourceRange().getBegin(),
1538 diag::err_template_arg_not_pointer_to_member_form)
1539 << Arg->getSourceRange();
1540
1541 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
1542 assert((isa<FieldDecl>(DRE->getDecl()) ||
1543 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
1544 "Only non-static member pointers can make it here");
1545
1546 // Okay: this is the address of a non-static member, and therefore
1547 // a member pointer constant.
Douglas Gregorad964b32009-02-17 01:05:43 +00001548 Member = DRE->getDecl();
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001549 return Invalid;
1550 }
1551
1552 // We found something else, but we don't know specifically what it is.
1553 Diag(Arg->getSourceRange().getBegin(),
1554 diag::err_template_arg_not_pointer_to_member_form)
1555 << Arg->getSourceRange();
1556 Diag(DRE->getDecl()->getLocation(),
1557 diag::note_template_arg_refers_here);
1558 return true;
1559}
1560
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001561/// \brief Check a template argument against its corresponding
1562/// non-type template parameter.
1563///
Douglas Gregored3a3982009-03-03 04:44:36 +00001564/// This routine implements the semantics of C++ [temp.arg.nontype].
1565/// It returns true if an error occurred, and false otherwise. \p
1566/// InstantiatedParamType is the type of the non-type template
1567/// parameter after it has been instantiated.
Douglas Gregorad964b32009-02-17 01:05:43 +00001568///
Douglas Gregor8f378a92009-06-11 18:10:32 +00001569/// If no error was detected, Converted receives the converted template argument.
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001570bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Douglas Gregored3a3982009-03-03 04:44:36 +00001571 QualType InstantiatedParamType, Expr *&Arg,
Douglas Gregor8f378a92009-06-11 18:10:32 +00001572 TemplateArgument &Converted) {
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001573 SourceLocation StartLoc = Arg->getSourceRange().getBegin();
1574
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001575 // If either the parameter has a dependent type or the argument is
1576 // type-dependent, there's nothing we can check now.
Douglas Gregorad964b32009-02-17 01:05:43 +00001577 // FIXME: Add template argument to Converted!
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001578 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
1579 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor8f378a92009-06-11 18:10:32 +00001580 Converted = TemplateArgument(Arg);
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001581 return false;
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001582 }
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001583
1584 // C++ [temp.arg.nontype]p5:
1585 // The following conversions are performed on each expression used
1586 // as a non-type template-argument. If a non-type
1587 // template-argument cannot be converted to the type of the
1588 // corresponding template-parameter then the program is
1589 // ill-formed.
1590 //
1591 // -- for a non-type template-parameter of integral or
1592 // enumeration type, integral promotions (4.5) and integral
1593 // conversions (4.7) are applied.
Douglas Gregored3a3982009-03-03 04:44:36 +00001594 QualType ParamType = InstantiatedParamType;
Douglas Gregor2eedd992009-02-11 00:19:33 +00001595 QualType ArgType = Arg->getType();
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001596 if (ParamType->isIntegralType() || ParamType->isEnumeralType()) {
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001597 // C++ [temp.arg.nontype]p1:
1598 // A template-argument for a non-type, non-template
1599 // template-parameter shall be one of:
1600 //
1601 // -- an integral constant-expression of integral or enumeration
1602 // type; or
1603 // -- the name of a non-type template-parameter; or
1604 SourceLocation NonConstantLoc;
Douglas Gregorad964b32009-02-17 01:05:43 +00001605 llvm::APSInt Value;
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001606 if (!ArgType->isIntegralType() && !ArgType->isEnumeralType()) {
1607 Diag(Arg->getSourceRange().getBegin(),
1608 diag::err_template_arg_not_integral_or_enumeral)
1609 << ArgType << Arg->getSourceRange();
1610 Diag(Param->getLocation(), diag::note_template_param_here);
1611 return true;
1612 } else if (!Arg->isValueDependent() &&
Douglas Gregorad964b32009-02-17 01:05:43 +00001613 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001614 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
1615 << ArgType << Arg->getSourceRange();
1616 return true;
1617 }
1618
1619 // FIXME: We need some way to more easily get the unqualified form
1620 // of the types without going all the way to the
1621 // canonical type.
1622 if (Context.getCanonicalType(ParamType).getCVRQualifiers())
1623 ParamType = Context.getCanonicalType(ParamType).getUnqualifiedType();
1624 if (Context.getCanonicalType(ArgType).getCVRQualifiers())
1625 ArgType = Context.getCanonicalType(ArgType).getUnqualifiedType();
1626
1627 // Try to convert the argument to the parameter's type.
1628 if (ParamType == ArgType) {
1629 // Okay: no conversion necessary
1630 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
1631 !ParamType->isEnumeralType()) {
1632 // This is an integral promotion or conversion.
1633 ImpCastExprToType(Arg, ParamType);
1634 } else {
1635 // We can't perform this conversion.
1636 Diag(Arg->getSourceRange().getBegin(),
1637 diag::err_template_arg_not_convertible)
Douglas Gregored3a3982009-03-03 04:44:36 +00001638 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001639 Diag(Param->getLocation(), diag::note_template_param_here);
1640 return true;
1641 }
1642
Douglas Gregorafc86942009-03-14 00:20:21 +00001643 QualType IntegerType = Context.getCanonicalType(ParamType);
1644 if (const EnumType *Enum = IntegerType->getAsEnumType())
Douglas Gregor8f378a92009-06-11 18:10:32 +00001645 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregorafc86942009-03-14 00:20:21 +00001646
1647 if (!Arg->isValueDependent()) {
1648 // Check that an unsigned parameter does not receive a negative
1649 // value.
1650 if (IntegerType->isUnsignedIntegerType()
1651 && (Value.isSigned() && Value.isNegative())) {
1652 Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_negative)
1653 << Value.toString(10) << Param->getType()
1654 << Arg->getSourceRange();
1655 Diag(Param->getLocation(), diag::note_template_param_here);
1656 return true;
1657 }
1658
1659 // Check that we don't overflow the template parameter type.
1660 unsigned AllowedBits = Context.getTypeSize(IntegerType);
1661 if (Value.getActiveBits() > AllowedBits) {
1662 Diag(Arg->getSourceRange().getBegin(),
1663 diag::err_template_arg_too_large)
1664 << Value.toString(10) << Param->getType()
1665 << Arg->getSourceRange();
1666 Diag(Param->getLocation(), diag::note_template_param_here);
1667 return true;
1668 }
1669
1670 if (Value.getBitWidth() != AllowedBits)
1671 Value.extOrTrunc(AllowedBits);
1672 Value.setIsSigned(IntegerType->isSignedIntegerType());
1673 }
Douglas Gregorad964b32009-02-17 01:05:43 +00001674
Douglas Gregor8f378a92009-06-11 18:10:32 +00001675 // Add the value of this argument to the list of converted
1676 // arguments. We use the bitwidth and signedness of the template
1677 // parameter.
1678 if (Arg->isValueDependent()) {
1679 // The argument is value-dependent. Create a new
1680 // TemplateArgument with the converted expression.
1681 Converted = TemplateArgument(Arg);
1682 return false;
Douglas Gregorad964b32009-02-17 01:05:43 +00001683 }
1684
Douglas Gregor8f378a92009-06-11 18:10:32 +00001685 Converted = TemplateArgument(StartLoc, Value,
1686 ParamType->isEnumeralType() ? ParamType
1687 : IntegerType);
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001688 return false;
1689 }
Douglas Gregor2eedd992009-02-11 00:19:33 +00001690
Douglas Gregor3f411962009-02-11 01:18:59 +00001691 // Handle pointer-to-function, reference-to-function, and
1692 // pointer-to-member-function all in (roughly) the same way.
1693 if (// -- For a non-type template-parameter of type pointer to
1694 // function, only the function-to-pointer conversion (4.3) is
1695 // applied. If the template-argument represents a set of
1696 // overloaded functions (or a pointer to such), the matching
1697 // function is selected from the set (13.4).
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001698 // In C++0x, any std::nullptr_t value can be converted.
Douglas Gregor3f411962009-02-11 01:18:59 +00001699 (ParamType->isPointerType() &&
Ted Kremenekd9b39bf2009-07-17 17:50:17 +00001700 ParamType->getAsPointerType()->getPointeeType()->isFunctionType()) ||
Douglas Gregor3f411962009-02-11 01:18:59 +00001701 // -- For a non-type template-parameter of type reference to
1702 // function, no conversions apply. If the template-argument
1703 // represents a set of overloaded functions, the matching
1704 // function is selected from the set (13.4).
1705 (ParamType->isReferenceType() &&
Ted Kremenekd9b39bf2009-07-17 17:50:17 +00001706 ParamType->getAsReferenceType()->getPointeeType()->isFunctionType()) ||
Douglas Gregor3f411962009-02-11 01:18:59 +00001707 // -- For a non-type template-parameter of type pointer to
1708 // member function, no conversions apply. If the
1709 // template-argument represents a set of overloaded member
1710 // functions, the matching member function is selected from
1711 // the set (13.4).
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001712 // Again, C++0x allows a std::nullptr_t value.
Douglas Gregor3f411962009-02-11 01:18:59 +00001713 (ParamType->isMemberPointerType() &&
Ted Kremenekd9b39bf2009-07-17 17:50:17 +00001714 ParamType->getAsMemberPointerType()->getPointeeType()
Douglas Gregor3f411962009-02-11 01:18:59 +00001715 ->isFunctionType())) {
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001716 if (Context.hasSameUnqualifiedType(ArgType,
1717 ParamType.getNonReferenceType())) {
Douglas Gregor2eedd992009-02-11 00:19:33 +00001718 // We don't have to do anything: the types already match.
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001719 } else if (ArgType->isNullPtrType() && (ParamType->isPointerType() ||
1720 ParamType->isMemberPointerType())) {
1721 ArgType = ParamType;
1722 ImpCastExprToType(Arg, ParamType);
Douglas Gregor3f411962009-02-11 01:18:59 +00001723 } else if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregor2eedd992009-02-11 00:19:33 +00001724 ArgType = Context.getPointerType(ArgType);
1725 ImpCastExprToType(Arg, ArgType);
1726 } else if (FunctionDecl *Fn
1727 = ResolveAddressOfOverloadedFunction(Arg, ParamType, true)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00001728 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
1729 return true;
1730
Douglas Gregor2eedd992009-02-11 00:19:33 +00001731 FixOverloadedFunctionReference(Arg, Fn);
1732 ArgType = Arg->getType();
Douglas Gregor3f411962009-02-11 01:18:59 +00001733 if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregor2eedd992009-02-11 00:19:33 +00001734 ArgType = Context.getPointerType(Arg->getType());
1735 ImpCastExprToType(Arg, ArgType);
1736 }
1737 }
1738
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001739 if (!Context.hasSameUnqualifiedType(ArgType,
1740 ParamType.getNonReferenceType())) {
Douglas Gregor2eedd992009-02-11 00:19:33 +00001741 // We can't perform this conversion.
1742 Diag(Arg->getSourceRange().getBegin(),
1743 diag::err_template_arg_not_convertible)
Douglas Gregored3a3982009-03-03 04:44:36 +00001744 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor2eedd992009-02-11 00:19:33 +00001745 Diag(Param->getLocation(), diag::note_template_param_here);
1746 return true;
1747 }
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001748
Douglas Gregorad964b32009-02-17 01:05:43 +00001749 if (ParamType->isMemberPointerType()) {
1750 NamedDecl *Member = 0;
1751 if (CheckTemplateArgumentPointerToMember(Arg, Member))
1752 return true;
1753
Argiris Kirtzidis17c7cab2009-07-18 00:34:25 +00001754 if (Member)
1755 Member = cast<NamedDecl>(Member->getCanonicalDecl());
Douglas Gregor8f378a92009-06-11 18:10:32 +00001756 Converted = TemplateArgument(StartLoc, Member);
Douglas Gregorad964b32009-02-17 01:05:43 +00001757 return false;
1758 }
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001759
Douglas Gregorad964b32009-02-17 01:05:43 +00001760 NamedDecl *Entity = 0;
1761 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1762 return true;
1763
Argiris Kirtzidis17c7cab2009-07-18 00:34:25 +00001764 if (Entity)
1765 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
Douglas Gregor8f378a92009-06-11 18:10:32 +00001766 Converted = TemplateArgument(StartLoc, Entity);
Douglas Gregorad964b32009-02-17 01:05:43 +00001767 return false;
Douglas Gregor2eedd992009-02-11 00:19:33 +00001768 }
1769
Chris Lattner320dff22009-02-20 21:37:53 +00001770 if (ParamType->isPointerType()) {
Douglas Gregor3f411962009-02-11 01:18:59 +00001771 // -- for a non-type template-parameter of type pointer to
1772 // object, qualification conversions (4.4) and the
1773 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001774 // C++0x also allows a value of std::nullptr_t.
Ted Kremenekd9b39bf2009-07-17 17:50:17 +00001775 assert(ParamType->getAsPointerType()->getPointeeType()->isObjectType() &&
Douglas Gregor3f411962009-02-11 01:18:59 +00001776 "Only object pointers allowed here");
Douglas Gregord8c8c092009-02-11 00:44:29 +00001777
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001778 if (ArgType->isNullPtrType()) {
1779 ArgType = ParamType;
1780 ImpCastExprToType(Arg, ParamType);
1781 } else if (ArgType->isArrayType()) {
Douglas Gregor3f411962009-02-11 01:18:59 +00001782 ArgType = Context.getArrayDecayedType(ArgType);
1783 ImpCastExprToType(Arg, ArgType);
Douglas Gregord8c8c092009-02-11 00:44:29 +00001784 }
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001785
Douglas Gregor3f411962009-02-11 01:18:59 +00001786 if (IsQualificationConversion(ArgType, ParamType)) {
1787 ArgType = ParamType;
1788 ImpCastExprToType(Arg, ParamType);
1789 }
1790
Douglas Gregor0ea4e302009-02-11 18:22:40 +00001791 if (!Context.hasSameUnqualifiedType(ArgType, ParamType)) {
Douglas Gregor3f411962009-02-11 01:18:59 +00001792 // We can't perform this conversion.
1793 Diag(Arg->getSourceRange().getBegin(),
1794 diag::err_template_arg_not_convertible)
Douglas Gregored3a3982009-03-03 04:44:36 +00001795 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor3f411962009-02-11 01:18:59 +00001796 Diag(Param->getLocation(), diag::note_template_param_here);
1797 return true;
1798 }
1799
Douglas Gregorad964b32009-02-17 01:05:43 +00001800 NamedDecl *Entity = 0;
1801 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1802 return true;
1803
Argiris Kirtzidis17c7cab2009-07-18 00:34:25 +00001804 if (Entity)
1805 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
Douglas Gregor8f378a92009-06-11 18:10:32 +00001806 Converted = TemplateArgument(StartLoc, Entity);
Douglas Gregorad964b32009-02-17 01:05:43 +00001807 return false;
Douglas Gregord8c8c092009-02-11 00:44:29 +00001808 }
Douglas Gregor3f411962009-02-11 01:18:59 +00001809
Ted Kremenekd9b39bf2009-07-17 17:50:17 +00001810 if (const ReferenceType *ParamRefType = ParamType->getAsReferenceType()) {
Douglas Gregor3f411962009-02-11 01:18:59 +00001811 // -- For a non-type template-parameter of type reference to
1812 // object, no conversions apply. The type referred to by the
1813 // reference may be more cv-qualified than the (otherwise
1814 // identical) type of the template-argument. The
1815 // template-parameter is bound directly to the
1816 // template-argument, which must be an lvalue.
Douglas Gregor26ea1222009-03-24 20:32:41 +00001817 assert(ParamRefType->getPointeeType()->isObjectType() &&
Douglas Gregor3f411962009-02-11 01:18:59 +00001818 "Only object references allowed here");
Douglas Gregord8c8c092009-02-11 00:44:29 +00001819
Douglas Gregor0ea4e302009-02-11 18:22:40 +00001820 if (!Context.hasSameUnqualifiedType(ParamRefType->getPointeeType(), ArgType)) {
Douglas Gregor3f411962009-02-11 01:18:59 +00001821 Diag(Arg->getSourceRange().getBegin(),
1822 diag::err_template_arg_no_ref_bind)
Douglas Gregored3a3982009-03-03 04:44:36 +00001823 << InstantiatedParamType << Arg->getType()
Douglas Gregor3f411962009-02-11 01:18:59 +00001824 << Arg->getSourceRange();
1825 Diag(Param->getLocation(), diag::note_template_param_here);
1826 return true;
1827 }
1828
1829 unsigned ParamQuals
1830 = Context.getCanonicalType(ParamType).getCVRQualifiers();
1831 unsigned ArgQuals = Context.getCanonicalType(ArgType).getCVRQualifiers();
1832
1833 if ((ParamQuals | ArgQuals) != ParamQuals) {
1834 Diag(Arg->getSourceRange().getBegin(),
1835 diag::err_template_arg_ref_bind_ignores_quals)
Douglas Gregored3a3982009-03-03 04:44:36 +00001836 << InstantiatedParamType << Arg->getType()
Douglas Gregor3f411962009-02-11 01:18:59 +00001837 << Arg->getSourceRange();
1838 Diag(Param->getLocation(), diag::note_template_param_here);
1839 return true;
1840 }
1841
Douglas Gregorad964b32009-02-17 01:05:43 +00001842 NamedDecl *Entity = 0;
1843 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1844 return true;
1845
Argiris Kirtzidis17c7cab2009-07-18 00:34:25 +00001846 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
Douglas Gregor8f378a92009-06-11 18:10:32 +00001847 Converted = TemplateArgument(StartLoc, Entity);
Douglas Gregorad964b32009-02-17 01:05:43 +00001848 return false;
Douglas Gregor3f411962009-02-11 01:18:59 +00001849 }
Douglas Gregor3628e1b2009-02-11 16:16:59 +00001850
1851 // -- For a non-type template-parameter of type pointer to data
1852 // member, qualification conversions (4.4) are applied.
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001853 // C++0x allows std::nullptr_t values.
Douglas Gregor3628e1b2009-02-11 16:16:59 +00001854 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
1855
Douglas Gregor0ea4e302009-02-11 18:22:40 +00001856 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
Douglas Gregor3628e1b2009-02-11 16:16:59 +00001857 // Types match exactly: nothing more to do here.
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001858 } else if (ArgType->isNullPtrType()) {
1859 ImpCastExprToType(Arg, ParamType);
Douglas Gregor3628e1b2009-02-11 16:16:59 +00001860 } else if (IsQualificationConversion(ArgType, ParamType)) {
1861 ImpCastExprToType(Arg, ParamType);
1862 } else {
1863 // We can't perform this conversion.
1864 Diag(Arg->getSourceRange().getBegin(),
1865 diag::err_template_arg_not_convertible)
Douglas Gregored3a3982009-03-03 04:44:36 +00001866 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor3628e1b2009-02-11 16:16:59 +00001867 Diag(Param->getLocation(), diag::note_template_param_here);
1868 return true;
1869 }
1870
Douglas Gregorad964b32009-02-17 01:05:43 +00001871 NamedDecl *Member = 0;
1872 if (CheckTemplateArgumentPointerToMember(Arg, Member))
1873 return true;
1874
Argiris Kirtzidis17c7cab2009-07-18 00:34:25 +00001875 if (Member)
1876 Member = cast<NamedDecl>(Member->getCanonicalDecl());
Douglas Gregor8f378a92009-06-11 18:10:32 +00001877 Converted = TemplateArgument(StartLoc, Member);
Douglas Gregorad964b32009-02-17 01:05:43 +00001878 return false;
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001879}
1880
1881/// \brief Check a template argument against its corresponding
1882/// template template parameter.
1883///
1884/// This routine implements the semantics of C++ [temp.arg.template].
1885/// It returns true if an error occurred, and false otherwise.
1886bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
1887 DeclRefExpr *Arg) {
Douglas Gregore8e367f2009-02-10 00:24:35 +00001888 assert(isa<TemplateDecl>(Arg->getDecl()) && "Only template decls allowed");
1889 TemplateDecl *Template = cast<TemplateDecl>(Arg->getDecl());
1890
1891 // C++ [temp.arg.template]p1:
1892 // A template-argument for a template template-parameter shall be
1893 // the name of a class template, expressed as id-expression. Only
1894 // primary class templates are considered when matching the
1895 // template template argument with the corresponding parameter;
1896 // partial specializations are not considered even if their
1897 // parameter lists match that of the template template parameter.
Douglas Gregorfbcc9e92009-06-12 19:43:02 +00001898 //
1899 // Note that we also allow template template parameters here, which
1900 // will happen when we are dealing with, e.g., class template
1901 // partial specializations.
1902 if (!isa<ClassTemplateDecl>(Template) &&
1903 !isa<TemplateTemplateParmDecl>(Template)) {
Douglas Gregore8e367f2009-02-10 00:24:35 +00001904 assert(isa<FunctionTemplateDecl>(Template) &&
1905 "Only function templates are possible here");
Douglas Gregorb60eb752009-06-25 22:08:12 +00001906 Diag(Arg->getLocStart(), diag::err_template_arg_not_class_template);
1907 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
Douglas Gregore8e367f2009-02-10 00:24:35 +00001908 << Template;
1909 }
1910
1911 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
1912 Param->getTemplateParameters(),
1913 true, true,
1914 Arg->getSourceRange().getBegin());
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001915}
1916
Douglas Gregord406b032009-02-06 22:42:48 +00001917/// \brief Determine whether the given template parameter lists are
1918/// equivalent.
1919///
1920/// \param New The new template parameter list, typically written in the
1921/// source code as part of a new template declaration.
1922///
1923/// \param Old The old template parameter list, typically found via
1924/// name lookup of the template declared with this template parameter
1925/// list.
1926///
1927/// \param Complain If true, this routine will produce a diagnostic if
1928/// the template parameter lists are not equivalent.
1929///
Douglas Gregore8e367f2009-02-10 00:24:35 +00001930/// \param IsTemplateTemplateParm If true, this routine is being
1931/// called to compare the template parameter lists of a template
1932/// template parameter.
1933///
1934/// \param TemplateArgLoc If this source location is valid, then we
1935/// are actually checking the template parameter list of a template
1936/// argument (New) against the template parameter list of its
1937/// corresponding template template parameter (Old). We produce
1938/// slightly different diagnostics in this scenario.
1939///
Douglas Gregord406b032009-02-06 22:42:48 +00001940/// \returns True if the template parameter lists are equal, false
1941/// otherwise.
1942bool
1943Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
1944 TemplateParameterList *Old,
1945 bool Complain,
Douglas Gregore8e367f2009-02-10 00:24:35 +00001946 bool IsTemplateTemplateParm,
1947 SourceLocation TemplateArgLoc) {
Douglas Gregord406b032009-02-06 22:42:48 +00001948 if (Old->size() != New->size()) {
1949 if (Complain) {
Douglas Gregore8e367f2009-02-10 00:24:35 +00001950 unsigned NextDiag = diag::err_template_param_list_different_arity;
1951 if (TemplateArgLoc.isValid()) {
1952 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
1953 NextDiag = diag::note_template_param_list_different_arity;
1954 }
1955 Diag(New->getTemplateLoc(), NextDiag)
1956 << (New->size() > Old->size())
1957 << IsTemplateTemplateParm
1958 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
Douglas Gregord406b032009-02-06 22:42:48 +00001959 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
1960 << IsTemplateTemplateParm
1961 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
1962 }
1963
1964 return false;
1965 }
1966
1967 for (TemplateParameterList::iterator OldParm = Old->begin(),
1968 OldParmEnd = Old->end(), NewParm = New->begin();
1969 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
1970 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
Douglas Gregorbf6bc302009-06-24 16:50:40 +00001971 if (Complain) {
1972 unsigned NextDiag = diag::err_template_param_different_kind;
1973 if (TemplateArgLoc.isValid()) {
1974 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
1975 NextDiag = diag::note_template_param_different_kind;
1976 }
1977 Diag((*NewParm)->getLocation(), NextDiag)
1978 << IsTemplateTemplateParm;
1979 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
1980 << IsTemplateTemplateParm;
Douglas Gregore8e367f2009-02-10 00:24:35 +00001981 }
Douglas Gregord406b032009-02-06 22:42:48 +00001982 return false;
1983 }
1984
1985 if (isa<TemplateTypeParmDecl>(*OldParm)) {
1986 // Okay; all template type parameters are equivalent (since we
Douglas Gregore8e367f2009-02-10 00:24:35 +00001987 // know we're at the same index).
1988#if 0
Mike Stumpe127ae32009-05-16 07:39:55 +00001989 // FIXME: Enable this code in debug mode *after* we properly go through
1990 // and "instantiate" the template parameter lists of template template
1991 // parameters. It's only after this instantiation that (1) any dependent
1992 // types within the template parameter list of the template template
1993 // parameter can be checked, and (2) the template type parameter depths
Douglas Gregore8e367f2009-02-10 00:24:35 +00001994 // will match up.
Douglas Gregord406b032009-02-06 22:42:48 +00001995 QualType OldParmType
1996 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*OldParm));
1997 QualType NewParmType
1998 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*NewParm));
1999 assert(Context.getCanonicalType(OldParmType) ==
2000 Context.getCanonicalType(NewParmType) &&
2001 "type parameter mismatch?");
2002#endif
2003 } else if (NonTypeTemplateParmDecl *OldNTTP
2004 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
2005 // The types of non-type template parameters must agree.
2006 NonTypeTemplateParmDecl *NewNTTP
2007 = cast<NonTypeTemplateParmDecl>(*NewParm);
2008 if (Context.getCanonicalType(OldNTTP->getType()) !=
2009 Context.getCanonicalType(NewNTTP->getType())) {
2010 if (Complain) {
Douglas Gregore8e367f2009-02-10 00:24:35 +00002011 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
2012 if (TemplateArgLoc.isValid()) {
2013 Diag(TemplateArgLoc,
2014 diag::err_template_arg_template_params_mismatch);
2015 NextDiag = diag::note_template_nontype_parm_different_type;
2016 }
2017 Diag(NewNTTP->getLocation(), NextDiag)
Douglas Gregord406b032009-02-06 22:42:48 +00002018 << NewNTTP->getType()
2019 << IsTemplateTemplateParm;
2020 Diag(OldNTTP->getLocation(),
2021 diag::note_template_nontype_parm_prev_declaration)
2022 << OldNTTP->getType();
2023 }
2024 return false;
2025 }
2026 } else {
2027 // The template parameter lists of template template
2028 // parameters must agree.
2029 // FIXME: Could we perform a faster "type" comparison here?
2030 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
2031 "Only template template parameters handled here");
2032 TemplateTemplateParmDecl *OldTTP
2033 = cast<TemplateTemplateParmDecl>(*OldParm);
2034 TemplateTemplateParmDecl *NewTTP
2035 = cast<TemplateTemplateParmDecl>(*NewParm);
2036 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
2037 OldTTP->getTemplateParameters(),
2038 Complain,
Douglas Gregore8e367f2009-02-10 00:24:35 +00002039 /*IsTemplateTemplateParm=*/true,
2040 TemplateArgLoc))
Douglas Gregord406b032009-02-06 22:42:48 +00002041 return false;
2042 }
2043 }
2044
2045 return true;
2046}
2047
2048/// \brief Check whether a template can be declared within this scope.
2049///
2050/// If the template declaration is valid in this scope, returns
2051/// false. Otherwise, issues a diagnostic and returns true.
2052bool
2053Sema::CheckTemplateDeclScope(Scope *S,
2054 MultiTemplateParamsArg &TemplateParameterLists) {
2055 assert(TemplateParameterLists.size() > 0 && "Not a template");
2056
2057 // Find the nearest enclosing declaration scope.
2058 while ((S->getFlags() & Scope::DeclScope) == 0 ||
2059 (S->getFlags() & Scope::TemplateParamScope) != 0)
2060 S = S->getParent();
2061
2062 TemplateParameterList *TemplateParams =
2063 static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
2064 SourceLocation TemplateLoc = TemplateParams->getTemplateLoc();
2065 SourceRange TemplateRange
2066 = SourceRange(TemplateLoc, TemplateParams->getRAngleLoc());
2067
2068 // C++ [temp]p2:
2069 // A template-declaration can appear only as a namespace scope or
2070 // class scope declaration.
2071 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
2072 while (Ctx && isa<LinkageSpecDecl>(Ctx)) {
2073 if (cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
2074 return Diag(TemplateLoc, diag::err_template_linkage)
2075 << TemplateRange;
2076
2077 Ctx = Ctx->getParent();
2078 }
2079
2080 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
2081 return false;
2082
2083 return Diag(TemplateLoc, diag::err_template_outside_namespace_or_class_scope)
2084 << TemplateRange;
2085}
Douglas Gregora08b6c72009-02-17 23:15:12 +00002086
Douglas Gregor90177912009-05-13 18:28:20 +00002087/// \brief Check whether a class template specialization or explicit
2088/// instantiation in the current context is well-formed.
Douglas Gregor0d93f692009-02-25 22:02:03 +00002089///
Douglas Gregor90177912009-05-13 18:28:20 +00002090/// This routine determines whether a class template specialization or
2091/// explicit instantiation can be declared in the current context
2092/// (C++ [temp.expl.spec]p2, C++0x [temp.explicit]p2) and emits
2093/// appropriate diagnostics if there was an error. It returns true if
2094// there was an error that we cannot recover from, and false otherwise.
Douglas Gregor0d93f692009-02-25 22:02:03 +00002095bool
2096Sema::CheckClassTemplateSpecializationScope(ClassTemplateDecl *ClassTemplate,
2097 ClassTemplateSpecializationDecl *PrevDecl,
2098 SourceLocation TemplateNameLoc,
Douglas Gregor90177912009-05-13 18:28:20 +00002099 SourceRange ScopeSpecifierRange,
Douglas Gregor4faa4262009-06-12 22:21:45 +00002100 bool PartialSpecialization,
Douglas Gregor90177912009-05-13 18:28:20 +00002101 bool ExplicitInstantiation) {
Douglas Gregor0d93f692009-02-25 22:02:03 +00002102 // C++ [temp.expl.spec]p2:
2103 // An explicit specialization shall be declared in the namespace
2104 // of which the template is a member, or, for member templates, in
2105 // the namespace of which the enclosing class or enclosing class
2106 // template is a member. An explicit specialization of a member
2107 // function, member class or static data member of a class
2108 // template shall be declared in the namespace of which the class
2109 // template is a member. Such a declaration may also be a
2110 // definition. If the declaration is not a definition, the
2111 // specialization may be defined later in the name- space in which
2112 // the explicit specialization was declared, or in a namespace
2113 // that encloses the one in which the explicit specialization was
2114 // declared.
2115 if (CurContext->getLookupContext()->isFunctionOrMethod()) {
Douglas Gregor4faa4262009-06-12 22:21:45 +00002116 int Kind = ExplicitInstantiation? 2 : PartialSpecialization? 1 : 0;
Douglas Gregor0d93f692009-02-25 22:02:03 +00002117 Diag(TemplateNameLoc, diag::err_template_spec_decl_function_scope)
Douglas Gregor4faa4262009-06-12 22:21:45 +00002118 << Kind << ClassTemplate;
Douglas Gregor0d93f692009-02-25 22:02:03 +00002119 return true;
2120 }
2121
2122 DeclContext *DC = CurContext->getEnclosingNamespaceContext();
2123 DeclContext *TemplateContext
2124 = ClassTemplate->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregor90177912009-05-13 18:28:20 +00002125 if ((!PrevDecl || PrevDecl->getSpecializationKind() == TSK_Undeclared) &&
2126 !ExplicitInstantiation) {
Douglas Gregor0d93f692009-02-25 22:02:03 +00002127 // There is no prior declaration of this entity, so this
2128 // specialization must be in the same context as the template
2129 // itself.
2130 if (DC != TemplateContext) {
2131 if (isa<TranslationUnitDecl>(TemplateContext))
2132 Diag(TemplateNameLoc, diag::err_template_spec_decl_out_of_scope_global)
Douglas Gregor4faa4262009-06-12 22:21:45 +00002133 << PartialSpecialization
Douglas Gregor0d93f692009-02-25 22:02:03 +00002134 << ClassTemplate << ScopeSpecifierRange;
2135 else if (isa<NamespaceDecl>(TemplateContext))
2136 Diag(TemplateNameLoc, diag::err_template_spec_decl_out_of_scope)
Douglas Gregor4faa4262009-06-12 22:21:45 +00002137 << PartialSpecialization << ClassTemplate
2138 << cast<NamedDecl>(TemplateContext) << ScopeSpecifierRange;
Douglas Gregor0d93f692009-02-25 22:02:03 +00002139
2140 Diag(ClassTemplate->getLocation(), diag::note_template_decl_here);
2141 }
2142
2143 return false;
2144 }
2145
2146 // We have a previous declaration of this entity. Make sure that
2147 // this redeclaration (or definition) occurs in an enclosing namespace.
2148 if (!CurContext->Encloses(TemplateContext)) {
Mike Stumpe127ae32009-05-16 07:39:55 +00002149 // FIXME: In C++98, we would like to turn these errors into warnings,
2150 // dependent on a -Wc++0x flag.
Douglas Gregor90177912009-05-13 18:28:20 +00002151 bool SuppressedDiag = false;
Douglas Gregor4faa4262009-06-12 22:21:45 +00002152 int Kind = ExplicitInstantiation? 2 : PartialSpecialization? 1 : 0;
Douglas Gregor90177912009-05-13 18:28:20 +00002153 if (isa<TranslationUnitDecl>(TemplateContext)) {
2154 if (!ExplicitInstantiation || getLangOptions().CPlusPlus0x)
2155 Diag(TemplateNameLoc, diag::err_template_spec_redecl_global_scope)
Douglas Gregor4faa4262009-06-12 22:21:45 +00002156 << Kind << ClassTemplate << ScopeSpecifierRange;
Douglas Gregor90177912009-05-13 18:28:20 +00002157 else
2158 SuppressedDiag = true;
2159 } else if (isa<NamespaceDecl>(TemplateContext)) {
2160 if (!ExplicitInstantiation || getLangOptions().CPlusPlus0x)
2161 Diag(TemplateNameLoc, diag::err_template_spec_redecl_out_of_scope)
Douglas Gregor4faa4262009-06-12 22:21:45 +00002162 << Kind << ClassTemplate
Douglas Gregor90177912009-05-13 18:28:20 +00002163 << cast<NamedDecl>(TemplateContext) << ScopeSpecifierRange;
2164 else
2165 SuppressedDiag = true;
2166 }
Douglas Gregor0d93f692009-02-25 22:02:03 +00002167
Douglas Gregor90177912009-05-13 18:28:20 +00002168 if (!SuppressedDiag)
2169 Diag(ClassTemplate->getLocation(), diag::note_template_decl_here);
Douglas Gregor0d93f692009-02-25 22:02:03 +00002170 }
2171
2172 return false;
2173}
2174
Douglas Gregor76e79952009-06-12 21:21:02 +00002175/// \brief Check the non-type template arguments of a class template
2176/// partial specialization according to C++ [temp.class.spec]p9.
2177///
Douglas Gregor42476442009-06-12 22:08:06 +00002178/// \param TemplateParams the template parameters of the primary class
2179/// template.
2180///
2181/// \param TemplateArg the template arguments of the class template
2182/// partial specialization.
2183///
2184/// \param MirrorsPrimaryTemplate will be set true if the class
2185/// template partial specialization arguments are identical to the
2186/// implicit template arguments of the primary template. This is not
2187/// necessarily an error (C++0x), and it is left to the caller to diagnose
2188/// this condition when it is an error.
2189///
Douglas Gregor76e79952009-06-12 21:21:02 +00002190/// \returns true if there was an error, false otherwise.
2191bool Sema::CheckClassTemplatePartialSpecializationArgs(
2192 TemplateParameterList *TemplateParams,
Anders Carlsson13fac3f2009-06-13 18:20:51 +00002193 const TemplateArgumentListBuilder &TemplateArgs,
Douglas Gregor42476442009-06-12 22:08:06 +00002194 bool &MirrorsPrimaryTemplate) {
Douglas Gregor76e79952009-06-12 21:21:02 +00002195 // FIXME: the interface to this function will have to change to
2196 // accommodate variadic templates.
Douglas Gregor42476442009-06-12 22:08:06 +00002197 MirrorsPrimaryTemplate = true;
Anders Carlsson13fac3f2009-06-13 18:20:51 +00002198
Anders Carlssonb0fc9992009-06-23 01:26:57 +00002199 const TemplateArgument *ArgList = TemplateArgs.getFlatArguments();
Anders Carlsson13fac3f2009-06-13 18:20:51 +00002200
Douglas Gregor76e79952009-06-12 21:21:02 +00002201 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
Douglas Gregor42476442009-06-12 22:08:06 +00002202 // Determine whether the template argument list of the partial
2203 // specialization is identical to the implicit argument list of
2204 // the primary template. The caller may need to diagnostic this as
2205 // an error per C++ [temp.class.spec]p9b3.
2206 if (MirrorsPrimaryTemplate) {
2207 if (TemplateTypeParmDecl *TTP
2208 = dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(I))) {
2209 if (Context.getCanonicalType(Context.getTypeDeclType(TTP)) !=
Anders Carlsson13fac3f2009-06-13 18:20:51 +00002210 Context.getCanonicalType(ArgList[I].getAsType()))
Douglas Gregor42476442009-06-12 22:08:06 +00002211 MirrorsPrimaryTemplate = false;
2212 } else if (TemplateTemplateParmDecl *TTP
2213 = dyn_cast<TemplateTemplateParmDecl>(
2214 TemplateParams->getParam(I))) {
2215 // FIXME: We should settle on either Declaration storage or
2216 // Expression storage for template template parameters.
2217 TemplateTemplateParmDecl *ArgDecl
2218 = dyn_cast_or_null<TemplateTemplateParmDecl>(
Anders Carlsson13fac3f2009-06-13 18:20:51 +00002219 ArgList[I].getAsDecl());
Douglas Gregor42476442009-06-12 22:08:06 +00002220 if (!ArgDecl)
2221 if (DeclRefExpr *DRE
Anders Carlsson13fac3f2009-06-13 18:20:51 +00002222 = dyn_cast_or_null<DeclRefExpr>(ArgList[I].getAsExpr()))
Douglas Gregor42476442009-06-12 22:08:06 +00002223 ArgDecl = dyn_cast<TemplateTemplateParmDecl>(DRE->getDecl());
2224
2225 if (!ArgDecl ||
2226 ArgDecl->getIndex() != TTP->getIndex() ||
2227 ArgDecl->getDepth() != TTP->getDepth())
2228 MirrorsPrimaryTemplate = false;
2229 }
2230 }
2231
Douglas Gregor76e79952009-06-12 21:21:02 +00002232 NonTypeTemplateParmDecl *Param
2233 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
Douglas Gregor42476442009-06-12 22:08:06 +00002234 if (!Param) {
Douglas Gregor76e79952009-06-12 21:21:02 +00002235 continue;
Douglas Gregor42476442009-06-12 22:08:06 +00002236 }
2237
Anders Carlsson13fac3f2009-06-13 18:20:51 +00002238 Expr *ArgExpr = ArgList[I].getAsExpr();
Douglas Gregor42476442009-06-12 22:08:06 +00002239 if (!ArgExpr) {
2240 MirrorsPrimaryTemplate = false;
Douglas Gregor76e79952009-06-12 21:21:02 +00002241 continue;
Douglas Gregor42476442009-06-12 22:08:06 +00002242 }
Douglas Gregor76e79952009-06-12 21:21:02 +00002243
2244 // C++ [temp.class.spec]p8:
2245 // A non-type argument is non-specialized if it is the name of a
2246 // non-type parameter. All other non-type arguments are
2247 // specialized.
2248 //
2249 // Below, we check the two conditions that only apply to
2250 // specialized non-type arguments, so skip any non-specialized
2251 // arguments.
2252 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Douglas Gregor42476442009-06-12 22:08:06 +00002253 if (NonTypeTemplateParmDecl *NTTP
2254 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl())) {
2255 if (MirrorsPrimaryTemplate &&
2256 (Param->getIndex() != NTTP->getIndex() ||
2257 Param->getDepth() != NTTP->getDepth()))
2258 MirrorsPrimaryTemplate = false;
2259
Douglas Gregor76e79952009-06-12 21:21:02 +00002260 continue;
Douglas Gregor42476442009-06-12 22:08:06 +00002261 }
Douglas Gregor76e79952009-06-12 21:21:02 +00002262
2263 // C++ [temp.class.spec]p9:
2264 // Within the argument list of a class template partial
2265 // specialization, the following restrictions apply:
2266 // -- A partially specialized non-type argument expression
2267 // shall not involve a template parameter of the partial
2268 // specialization except when the argument expression is a
2269 // simple identifier.
2270 if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
2271 Diag(ArgExpr->getLocStart(),
2272 diag::err_dependent_non_type_arg_in_partial_spec)
2273 << ArgExpr->getSourceRange();
2274 return true;
2275 }
2276
2277 // -- The type of a template parameter corresponding to a
2278 // specialized non-type argument shall not be dependent on a
2279 // parameter of the specialization.
2280 if (Param->getType()->isDependentType()) {
2281 Diag(ArgExpr->getLocStart(),
2282 diag::err_dependent_typed_non_type_arg_in_partial_spec)
2283 << Param->getType()
2284 << ArgExpr->getSourceRange();
2285 Diag(Param->getLocation(), diag::note_template_param_here);
2286 return true;
2287 }
Douglas Gregor42476442009-06-12 22:08:06 +00002288
2289 MirrorsPrimaryTemplate = false;
Douglas Gregor76e79952009-06-12 21:21:02 +00002290 }
2291
2292 return false;
2293}
2294
Douglas Gregorc5d6fa72009-03-25 00:13:59 +00002295Sema::DeclResult
Douglas Gregora08b6c72009-02-17 23:15:12 +00002296Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec, TagKind TK,
2297 SourceLocation KWLoc,
2298 const CXXScopeSpec &SS,
Douglas Gregordd13e842009-03-30 22:58:21 +00002299 TemplateTy TemplateD,
Douglas Gregora08b6c72009-02-17 23:15:12 +00002300 SourceLocation TemplateNameLoc,
2301 SourceLocation LAngleLoc,
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00002302 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregora08b6c72009-02-17 23:15:12 +00002303 SourceLocation *TemplateArgLocs,
2304 SourceLocation RAngleLoc,
2305 AttributeList *Attr,
2306 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregora08b6c72009-02-17 23:15:12 +00002307 // Find the class template we're specializing
Douglas Gregordd13e842009-03-30 22:58:21 +00002308 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Douglas Gregora08b6c72009-02-17 23:15:12 +00002309 ClassTemplateDecl *ClassTemplate
Douglas Gregordd13e842009-03-30 22:58:21 +00002310 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
Douglas Gregora08b6c72009-02-17 23:15:12 +00002311
Douglas Gregor58944ac2009-05-31 09:31:02 +00002312 bool isPartialSpecialization = false;
2313
Douglas Gregor0d93f692009-02-25 22:02:03 +00002314 // Check the validity of the template headers that introduce this
2315 // template.
Douglas Gregor50113ca2009-02-25 22:18:32 +00002316 // FIXME: Once we have member templates, we'll need to check
2317 // C++ [temp.expl.spec]p17-18, where we could have multiple levels of
2318 // template<> headers.
Douglas Gregor3bb30002009-02-26 21:00:50 +00002319 if (TemplateParameterLists.size() == 0)
2320 Diag(KWLoc, diag::err_template_spec_needs_header)
Douglas Gregor61be3602009-02-27 17:53:17 +00002321 << CodeModificationHint::CreateInsertion(KWLoc, "template<> ");
Douglas Gregor3bb30002009-02-26 21:00:50 +00002322 else {
Douglas Gregor0d93f692009-02-25 22:02:03 +00002323 TemplateParameterList *TemplateParams
2324 = static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
Chris Lattner5261d0c2009-03-28 19:18:32 +00002325 if (TemplateParameterLists.size() > 1) {
2326 Diag(TemplateParams->getTemplateLoc(),
2327 diag::err_template_spec_extra_headers);
2328 return true;
2329 }
Douglas Gregor0d93f692009-02-25 22:02:03 +00002330
Douglas Gregorfbcc9e92009-06-12 19:43:02 +00002331 if (TemplateParams->size() > 0) {
Douglas Gregor58944ac2009-05-31 09:31:02 +00002332 isPartialSpecialization = true;
Douglas Gregorfbcc9e92009-06-12 19:43:02 +00002333
2334 // C++ [temp.class.spec]p10:
2335 // The template parameter list of a specialization shall not
2336 // contain default template argument values.
2337 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
2338 Decl *Param = TemplateParams->getParam(I);
2339 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
2340 if (TTP->hasDefaultArgument()) {
2341 Diag(TTP->getDefaultArgumentLoc(),
2342 diag::err_default_arg_in_partial_spec);
2343 TTP->setDefaultArgument(QualType(), SourceLocation(), false);
2344 }
2345 } else if (NonTypeTemplateParmDecl *NTTP
2346 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2347 if (Expr *DefArg = NTTP->getDefaultArgument()) {
2348 Diag(NTTP->getDefaultArgumentLoc(),
2349 diag::err_default_arg_in_partial_spec)
2350 << DefArg->getSourceRange();
2351 NTTP->setDefaultArgument(0);
2352 DefArg->Destroy(Context);
2353 }
2354 } else {
2355 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
2356 if (Expr *DefArg = TTP->getDefaultArgument()) {
2357 Diag(TTP->getDefaultArgumentLoc(),
2358 diag::err_default_arg_in_partial_spec)
2359 << DefArg->getSourceRange();
2360 TTP->setDefaultArgument(0);
2361 DefArg->Destroy(Context);
2362 }
2363 }
2364 }
2365 }
Douglas Gregor0d93f692009-02-25 22:02:03 +00002366 }
2367
Douglas Gregora08b6c72009-02-17 23:15:12 +00002368 // Check that the specialization uses the same tag kind as the
2369 // original template.
2370 TagDecl::TagKind Kind;
2371 switch (TagSpec) {
2372 default: assert(0 && "Unknown tag type!");
2373 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2374 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2375 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2376 }
Douglas Gregor625185c2009-05-14 16:41:31 +00002377 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
2378 Kind, KWLoc,
2379 *ClassTemplate->getIdentifier())) {
Douglas Gregor3faaa812009-04-01 23:51:29 +00002380 Diag(KWLoc, diag::err_use_with_wrong_tag)
2381 << ClassTemplate
2382 << CodeModificationHint::CreateReplacement(KWLoc,
2383 ClassTemplate->getTemplatedDecl()->getKindName());
Douglas Gregora08b6c72009-02-17 23:15:12 +00002384 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
2385 diag::note_previous_use);
2386 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
2387 }
2388
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00002389 // Translate the parser's template argument list in our AST format.
2390 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
2391 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
2392
Douglas Gregora08b6c72009-02-17 23:15:12 +00002393 // Check that the template argument list is well-formed for this
2394 // template.
Anders Carlssonb0fc9992009-06-23 01:26:57 +00002395 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
2396 TemplateArgs.size());
Douglas Gregora08b6c72009-02-17 23:15:12 +00002397 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
Anders Carlsson13fac3f2009-06-13 18:20:51 +00002398 TemplateArgs.data(), TemplateArgs.size(),
Douglas Gregorecd63b82009-07-01 00:28:38 +00002399 RAngleLoc, false, Converted))
Douglas Gregorc5d6fa72009-03-25 00:13:59 +00002400 return true;
Douglas Gregora08b6c72009-02-17 23:15:12 +00002401
Anders Carlssonb0fc9992009-06-23 01:26:57 +00002402 assert((Converted.structuredSize() ==
Douglas Gregora08b6c72009-02-17 23:15:12 +00002403 ClassTemplate->getTemplateParameters()->size()) &&
2404 "Converted template argument list is too short!");
2405
Douglas Gregor58944ac2009-05-31 09:31:02 +00002406 // Find the class template (partial) specialization declaration that
Douglas Gregora08b6c72009-02-17 23:15:12 +00002407 // corresponds to these arguments.
2408 llvm::FoldingSetNodeID ID;
Douglas Gregorfbcc9e92009-06-12 19:43:02 +00002409 if (isPartialSpecialization) {
Douglas Gregor42476442009-06-12 22:08:06 +00002410 bool MirrorsPrimaryTemplate;
Douglas Gregor76e79952009-06-12 21:21:02 +00002411 if (CheckClassTemplatePartialSpecializationArgs(
2412 ClassTemplate->getTemplateParameters(),
Anders Carlssonb0fc9992009-06-23 01:26:57 +00002413 Converted, MirrorsPrimaryTemplate))
Douglas Gregor76e79952009-06-12 21:21:02 +00002414 return true;
2415
Douglas Gregor42476442009-06-12 22:08:06 +00002416 if (MirrorsPrimaryTemplate) {
2417 // C++ [temp.class.spec]p9b3:
2418 //
2419 // -- The argument list of the specialization shall not be identical
2420 // to the implicit argument list of the primary template.
2421 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
2422 << (TK == TK_Definition)
2423 << CodeModificationHint::CreateRemoval(SourceRange(LAngleLoc,
2424 RAngleLoc));
Douglas Gregor95254bc2009-07-23 16:36:45 +00002425 return CheckClassTemplate(S, TagSpec, TK, KWLoc, SS,
Douglas Gregor42476442009-06-12 22:08:06 +00002426 ClassTemplate->getIdentifier(),
2427 TemplateNameLoc,
2428 Attr,
2429 move(TemplateParameterLists),
2430 AS_none);
2431 }
2432
Douglas Gregor58944ac2009-05-31 09:31:02 +00002433 // FIXME: Template parameter list matters, too
Anders Carlssona35faf92009-06-05 03:43:12 +00002434 ClassTemplatePartialSpecializationDecl::Profile(ID,
Anders Carlssonb0fc9992009-06-23 01:26:57 +00002435 Converted.getFlatArguments(),
2436 Converted.flatSize());
Douglas Gregorfbcc9e92009-06-12 19:43:02 +00002437 }
Douglas Gregor58944ac2009-05-31 09:31:02 +00002438 else
Anders Carlssona35faf92009-06-05 03:43:12 +00002439 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlssonb0fc9992009-06-23 01:26:57 +00002440 Converted.getFlatArguments(),
2441 Converted.flatSize());
Douglas Gregora08b6c72009-02-17 23:15:12 +00002442 void *InsertPos = 0;
Douglas Gregor58944ac2009-05-31 09:31:02 +00002443 ClassTemplateSpecializationDecl *PrevDecl = 0;
2444
2445 if (isPartialSpecialization)
2446 PrevDecl
2447 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
2448 InsertPos);
2449 else
2450 PrevDecl
2451 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregora08b6c72009-02-17 23:15:12 +00002452
2453 ClassTemplateSpecializationDecl *Specialization = 0;
2454
Douglas Gregor0d93f692009-02-25 22:02:03 +00002455 // Check whether we can declare a class template specialization in
2456 // the current scope.
2457 if (CheckClassTemplateSpecializationScope(ClassTemplate, PrevDecl,
2458 TemplateNameLoc,
Douglas Gregor90177912009-05-13 18:28:20 +00002459 SS.getRange(),
Douglas Gregor4faa4262009-06-12 22:21:45 +00002460 isPartialSpecialization,
Douglas Gregor90177912009-05-13 18:28:20 +00002461 /*ExplicitInstantiation=*/false))
Douglas Gregorc5d6fa72009-03-25 00:13:59 +00002462 return true;
Douglas Gregor0d93f692009-02-25 22:02:03 +00002463
Douglas Gregora08b6c72009-02-17 23:15:12 +00002464 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
2465 // Since the only prior class template specialization with these
2466 // arguments was referenced but not declared, reuse that
2467 // declaration node as our own, updating its source location to
2468 // reflect our new declaration.
Douglas Gregora08b6c72009-02-17 23:15:12 +00002469 Specialization = PrevDecl;
Douglas Gregor50113ca2009-02-25 22:18:32 +00002470 Specialization->setLocation(TemplateNameLoc);
Douglas Gregora08b6c72009-02-17 23:15:12 +00002471 PrevDecl = 0;
Douglas Gregor58944ac2009-05-31 09:31:02 +00002472 } else if (isPartialSpecialization) {
Douglas Gregor58944ac2009-05-31 09:31:02 +00002473 // Create a new class template partial specialization declaration node.
2474 TemplateParameterList *TemplateParams
2475 = static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
2476 ClassTemplatePartialSpecializationDecl *PrevPartial
2477 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
2478 ClassTemplatePartialSpecializationDecl *Partial
2479 = ClassTemplatePartialSpecializationDecl::Create(Context,
2480 ClassTemplate->getDeclContext(),
Anders Carlsson6e9d02f2009-06-05 04:06:48 +00002481 TemplateNameLoc,
2482 TemplateParams,
2483 ClassTemplate,
Anders Carlssonb0fc9992009-06-23 01:26:57 +00002484 Converted,
Anders Carlsson6e9d02f2009-06-05 04:06:48 +00002485 PrevPartial);
Douglas Gregor58944ac2009-05-31 09:31:02 +00002486
2487 if (PrevPartial) {
2488 ClassTemplate->getPartialSpecializations().RemoveNode(PrevPartial);
2489 ClassTemplate->getPartialSpecializations().GetOrInsertNode(Partial);
2490 } else {
2491 ClassTemplate->getPartialSpecializations().InsertNode(Partial, InsertPos);
2492 }
2493 Specialization = Partial;
Douglas Gregorf90c2132009-06-13 00:26:55 +00002494
2495 // Check that all of the template parameters of the class template
2496 // partial specialization are deducible from the template
2497 // arguments. If not, this class template partial specialization
2498 // will never be used.
2499 llvm::SmallVector<bool, 8> DeducibleParams;
2500 DeducibleParams.resize(TemplateParams->size());
2501 MarkDeducedTemplateParameters(Partial->getTemplateArgs(), DeducibleParams);
2502 unsigned NumNonDeducible = 0;
2503 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I)
2504 if (!DeducibleParams[I])
2505 ++NumNonDeducible;
2506
2507 if (NumNonDeducible) {
2508 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
2509 << (NumNonDeducible > 1)
2510 << SourceRange(TemplateNameLoc, RAngleLoc);
2511 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
2512 if (!DeducibleParams[I]) {
2513 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
2514 if (Param->getDeclName())
2515 Diag(Param->getLocation(),
2516 diag::note_partial_spec_unused_parameter)
2517 << Param->getDeclName();
2518 else
2519 Diag(Param->getLocation(),
2520 diag::note_partial_spec_unused_parameter)
2521 << std::string("<anonymous>");
2522 }
2523 }
2524 }
2525
Douglas Gregora08b6c72009-02-17 23:15:12 +00002526 } else {
2527 // Create a new class template specialization declaration node for
2528 // this explicit specialization.
2529 Specialization
2530 = ClassTemplateSpecializationDecl::Create(Context,
2531 ClassTemplate->getDeclContext(),
2532 TemplateNameLoc,
Anders Carlsson6e9d02f2009-06-05 04:06:48 +00002533 ClassTemplate,
Anders Carlssonb0fc9992009-06-23 01:26:57 +00002534 Converted,
Douglas Gregora08b6c72009-02-17 23:15:12 +00002535 PrevDecl);
2536
2537 if (PrevDecl) {
2538 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
2539 ClassTemplate->getSpecializations().GetOrInsertNode(Specialization);
2540 } else {
2541 ClassTemplate->getSpecializations().InsertNode(Specialization,
2542 InsertPos);
2543 }
2544 }
2545
2546 // Note that this is an explicit specialization.
2547 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
2548
2549 // Check that this isn't a redefinition of this specialization.
2550 if (TK == TK_Definition) {
2551 if (RecordDecl *Def = Specialization->getDefinition(Context)) {
Mike Stumpe127ae32009-05-16 07:39:55 +00002552 // FIXME: Should also handle explicit specialization after implicit
2553 // instantiation with a special diagnostic.
Douglas Gregora08b6c72009-02-17 23:15:12 +00002554 SourceRange Range(TemplateNameLoc, RAngleLoc);
2555 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregor58944ac2009-05-31 09:31:02 +00002556 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregora08b6c72009-02-17 23:15:12 +00002557 Diag(Def->getLocation(), diag::note_previous_definition);
2558 Specialization->setInvalidDecl();
Douglas Gregorc5d6fa72009-03-25 00:13:59 +00002559 return true;
Douglas Gregora08b6c72009-02-17 23:15:12 +00002560 }
2561 }
2562
Douglas Gregor9c7825b2009-02-26 22:19:44 +00002563 // Build the fully-sugared type for this class template
2564 // specialization as the user wrote in the specialization
2565 // itself. This means that we'll pretty-print the type retrieved
2566 // from the specialization's declaration the way that the user
2567 // actually wrote the specialization, rather than formatting the
2568 // name based on the "canonical" representation used to store the
2569 // template arguments in the specialization.
Douglas Gregor8c795a12009-03-19 00:39:20 +00002570 QualType WrittenTy
Douglas Gregordd13e842009-03-30 22:58:21 +00002571 = Context.getTemplateSpecializationType(Name,
Anders Carlsson13fac3f2009-06-13 18:20:51 +00002572 TemplateArgs.data(),
Douglas Gregordd13e842009-03-30 22:58:21 +00002573 TemplateArgs.size(),
Douglas Gregor8c795a12009-03-19 00:39:20 +00002574 Context.getTypeDeclType(Specialization));
Douglas Gregordd13e842009-03-30 22:58:21 +00002575 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00002576 TemplateArgsIn.release();
Douglas Gregora08b6c72009-02-17 23:15:12 +00002577
Douglas Gregor50113ca2009-02-25 22:18:32 +00002578 // C++ [temp.expl.spec]p9:
2579 // A template explicit specialization is in the scope of the
2580 // namespace in which the template was defined.
2581 //
2582 // We actually implement this paragraph where we set the semantic
2583 // context (in the creation of the ClassTemplateSpecializationDecl),
2584 // but we also maintain the lexical context where the actual
2585 // definition occurs.
Douglas Gregora08b6c72009-02-17 23:15:12 +00002586 Specialization->setLexicalDeclContext(CurContext);
2587
2588 // We may be starting the definition of this specialization.
2589 if (TK == TK_Definition)
2590 Specialization->startDefinition();
2591
2592 // Add the specialization into its lexical context, so that it can
2593 // be seen when iterating through the list of declarations in that
2594 // context. However, specializations are not found by name lookup.
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002595 CurContext->addDecl(Specialization);
Chris Lattner5261d0c2009-03-28 19:18:32 +00002596 return DeclPtrTy::make(Specialization);
Douglas Gregora08b6c72009-02-17 23:15:12 +00002597}
Douglas Gregord3022602009-03-27 23:10:48 +00002598
Douglas Gregor2ae1d772009-06-23 23:11:28 +00002599Sema::DeclPtrTy
2600Sema::ActOnTemplateDeclarator(Scope *S,
2601 MultiTemplateParamsArg TemplateParameterLists,
2602 Declarator &D) {
2603 return HandleDeclarator(S, D, move(TemplateParameterLists), false);
2604}
2605
Douglas Gregor19d10652009-06-24 00:54:41 +00002606Sema::DeclPtrTy
2607Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
2608 MultiTemplateParamsArg TemplateParameterLists,
2609 Declarator &D) {
2610 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
2611 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
2612 "Not a function declarator!");
2613 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2614
2615 if (FTI.hasPrototype) {
2616 // FIXME: Diagnose arguments without names in C.
2617 }
2618
2619 Scope *ParentScope = FnBodyScope->getParent();
2620
2621 DeclPtrTy DP = HandleDeclarator(ParentScope, D,
2622 move(TemplateParameterLists),
2623 /*IsFunctionDefinition=*/true);
Douglas Gregorb462c322009-07-21 23:53:31 +00002624 if (FunctionTemplateDecl *FunctionTemplate
2625 = dyn_cast_or_null<FunctionTemplateDecl>(DP.getAs<Decl>()))
Douglas Gregorb60eb752009-06-25 22:08:12 +00002626 return ActOnStartOfFunctionDef(FnBodyScope,
2627 DeclPtrTy::make(FunctionTemplate->getTemplatedDecl()));
Douglas Gregorb462c322009-07-21 23:53:31 +00002628 if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(DP.getAs<Decl>()))
2629 return ActOnStartOfFunctionDef(FnBodyScope, DeclPtrTy::make(Function));
Douglas Gregorb60eb752009-06-25 22:08:12 +00002630 return DeclPtrTy();
Douglas Gregor19d10652009-06-24 00:54:41 +00002631}
2632
Douglas Gregor96b6df92009-05-14 00:28:11 +00002633// Explicit instantiation of a class template specialization
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002634Sema::DeclResult
2635Sema::ActOnExplicitInstantiation(Scope *S, SourceLocation TemplateLoc,
2636 unsigned TagSpec,
2637 SourceLocation KWLoc,
2638 const CXXScopeSpec &SS,
2639 TemplateTy TemplateD,
2640 SourceLocation TemplateNameLoc,
2641 SourceLocation LAngleLoc,
2642 ASTTemplateArgsPtr TemplateArgsIn,
2643 SourceLocation *TemplateArgLocs,
2644 SourceLocation RAngleLoc,
2645 AttributeList *Attr) {
2646 // Find the class template we're specializing
2647 TemplateName Name = TemplateD.getAsVal<TemplateName>();
2648 ClassTemplateDecl *ClassTemplate
2649 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
2650
2651 // Check that the specialization uses the same tag kind as the
2652 // original template.
2653 TagDecl::TagKind Kind;
2654 switch (TagSpec) {
2655 default: assert(0 && "Unknown tag type!");
2656 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2657 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2658 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2659 }
Douglas Gregor625185c2009-05-14 16:41:31 +00002660 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
2661 Kind, KWLoc,
2662 *ClassTemplate->getIdentifier())) {
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002663 Diag(KWLoc, diag::err_use_with_wrong_tag)
2664 << ClassTemplate
2665 << CodeModificationHint::CreateReplacement(KWLoc,
2666 ClassTemplate->getTemplatedDecl()->getKindName());
2667 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
2668 diag::note_previous_use);
2669 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
2670 }
2671
Douglas Gregor90177912009-05-13 18:28:20 +00002672 // C++0x [temp.explicit]p2:
2673 // [...] An explicit instantiation shall appear in an enclosing
2674 // namespace of its template. [...]
2675 //
2676 // This is C++ DR 275.
2677 if (CheckClassTemplateSpecializationScope(ClassTemplate, 0,
2678 TemplateNameLoc,
2679 SS.getRange(),
Douglas Gregor4faa4262009-06-12 22:21:45 +00002680 /*PartialSpecialization=*/false,
Douglas Gregor90177912009-05-13 18:28:20 +00002681 /*ExplicitInstantiation=*/true))
2682 return true;
2683
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002684 // Translate the parser's template argument list in our AST format.
2685 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
2686 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
2687
2688 // Check that the template argument list is well-formed for this
2689 // template.
Anders Carlssonb0fc9992009-06-23 01:26:57 +00002690 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
2691 TemplateArgs.size());
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002692 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
Anders Carlssonb912b392009-06-05 02:12:32 +00002693 TemplateArgs.data(), TemplateArgs.size(),
Douglas Gregorecd63b82009-07-01 00:28:38 +00002694 RAngleLoc, false, Converted))
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002695 return true;
2696
Anders Carlssonb0fc9992009-06-23 01:26:57 +00002697 assert((Converted.structuredSize() ==
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002698 ClassTemplate->getTemplateParameters()->size()) &&
2699 "Converted template argument list is too short!");
2700
2701 // Find the class template specialization declaration that
2702 // corresponds to these arguments.
2703 llvm::FoldingSetNodeID ID;
Anders Carlssona35faf92009-06-05 03:43:12 +00002704 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlssonb0fc9992009-06-23 01:26:57 +00002705 Converted.getFlatArguments(),
2706 Converted.flatSize());
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002707 void *InsertPos = 0;
2708 ClassTemplateSpecializationDecl *PrevDecl
2709 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
2710
2711 ClassTemplateSpecializationDecl *Specialization = 0;
2712
Douglas Gregor90177912009-05-13 18:28:20 +00002713 bool SpecializationRequiresInstantiation = true;
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002714 if (PrevDecl) {
Douglas Gregor90177912009-05-13 18:28:20 +00002715 if (PrevDecl->getSpecializationKind() == TSK_ExplicitInstantiation) {
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002716 // This particular specialization has already been declared or
2717 // instantiated. We cannot explicitly instantiate it.
Douglas Gregor90177912009-05-13 18:28:20 +00002718 Diag(TemplateNameLoc, diag::err_explicit_instantiation_duplicate)
2719 << Context.getTypeDeclType(PrevDecl);
2720 Diag(PrevDecl->getLocation(),
2721 diag::note_previous_explicit_instantiation);
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002722 return DeclPtrTy::make(PrevDecl);
2723 }
2724
Douglas Gregor90177912009-05-13 18:28:20 +00002725 if (PrevDecl->getSpecializationKind() == TSK_ExplicitSpecialization) {
Douglas Gregor96b6df92009-05-14 00:28:11 +00002726 // C++ DR 259, C++0x [temp.explicit]p4:
Douglas Gregor90177912009-05-13 18:28:20 +00002727 // For a given set of template parameters, if an explicit
2728 // instantiation of a template appears after a declaration of
2729 // an explicit specialization for that template, the explicit
2730 // instantiation has no effect.
2731 if (!getLangOptions().CPlusPlus0x) {
2732 Diag(TemplateNameLoc,
2733 diag::ext_explicit_instantiation_after_specialization)
2734 << Context.getTypeDeclType(PrevDecl);
2735 Diag(PrevDecl->getLocation(),
2736 diag::note_previous_template_specialization);
2737 }
2738
2739 // Create a new class template specialization declaration node
2740 // for this explicit specialization. This node is only used to
2741 // record the existence of this explicit instantiation for
2742 // accurate reproduction of the source code; we don't actually
2743 // use it for anything, since it is semantically irrelevant.
2744 Specialization
2745 = ClassTemplateSpecializationDecl::Create(Context,
2746 ClassTemplate->getDeclContext(),
2747 TemplateNameLoc,
2748 ClassTemplate,
Anders Carlssonb0fc9992009-06-23 01:26:57 +00002749 Converted, 0);
Douglas Gregor90177912009-05-13 18:28:20 +00002750 Specialization->setLexicalDeclContext(CurContext);
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002751 CurContext->addDecl(Specialization);
Douglas Gregor90177912009-05-13 18:28:20 +00002752 return DeclPtrTy::make(Specialization);
2753 }
2754
2755 // If we have already (implicitly) instantiated this
2756 // specialization, there is less work to do.
2757 if (PrevDecl->getSpecializationKind() == TSK_ImplicitInstantiation)
2758 SpecializationRequiresInstantiation = false;
2759
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002760 // Since the only prior class template specialization with these
2761 // arguments was referenced but not declared, reuse that
2762 // declaration node as our own, updating its source location to
2763 // reflect our new declaration.
2764 Specialization = PrevDecl;
2765 Specialization->setLocation(TemplateNameLoc);
2766 PrevDecl = 0;
2767 } else {
2768 // Create a new class template specialization declaration node for
2769 // this explicit specialization.
2770 Specialization
2771 = ClassTemplateSpecializationDecl::Create(Context,
2772 ClassTemplate->getDeclContext(),
2773 TemplateNameLoc,
2774 ClassTemplate,
Anders Carlssonb0fc9992009-06-23 01:26:57 +00002775 Converted, 0);
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002776
2777 ClassTemplate->getSpecializations().InsertNode(Specialization,
2778 InsertPos);
2779 }
2780
2781 // Build the fully-sugared type for this explicit instantiation as
2782 // the user wrote in the explicit instantiation itself. This means
2783 // that we'll pretty-print the type retrieved from the
2784 // specialization's declaration the way that the user actually wrote
2785 // the explicit instantiation, rather than formatting the name based
2786 // on the "canonical" representation used to store the template
2787 // arguments in the specialization.
2788 QualType WrittenTy
2789 = Context.getTemplateSpecializationType(Name,
Anders Carlssonefbff322009-06-05 02:45:24 +00002790 TemplateArgs.data(),
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002791 TemplateArgs.size(),
2792 Context.getTypeDeclType(Specialization));
2793 Specialization->setTypeAsWritten(WrittenTy);
2794 TemplateArgsIn.release();
2795
2796 // Add the explicit instantiation into its lexical context. However,
2797 // since explicit instantiations are never found by name lookup, we
2798 // just put it into the declaration context directly.
2799 Specialization->setLexicalDeclContext(CurContext);
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002800 CurContext->addDecl(Specialization);
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002801
2802 // C++ [temp.explicit]p3:
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002803 // A definition of a class template or class member template
2804 // shall be in scope at the point of the explicit instantiation of
2805 // the class template or class member template.
2806 //
2807 // This check comes when we actually try to perform the
2808 // instantiation.
Douglas Gregor556d8c72009-05-15 17:59:04 +00002809 if (SpecializationRequiresInstantiation)
2810 InstantiateClassTemplateSpecialization(Specialization, true);
Douglas Gregorb12249d2009-05-18 17:01:57 +00002811 else // Instantiate the members of this class template specialization.
Douglas Gregor556d8c72009-05-15 17:59:04 +00002812 InstantiateClassTemplateSpecializationMembers(TemplateLoc, Specialization);
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002813
2814 return DeclPtrTy::make(Specialization);
2815}
2816
Douglas Gregor96b6df92009-05-14 00:28:11 +00002817// Explicit instantiation of a member class of a class template.
2818Sema::DeclResult
2819Sema::ActOnExplicitInstantiation(Scope *S, SourceLocation TemplateLoc,
2820 unsigned TagSpec,
2821 SourceLocation KWLoc,
2822 const CXXScopeSpec &SS,
2823 IdentifierInfo *Name,
2824 SourceLocation NameLoc,
2825 AttributeList *Attr) {
2826
Douglas Gregor71f06032009-05-28 23:31:59 +00002827 bool Owned = false;
Douglas Gregor96b6df92009-05-14 00:28:11 +00002828 DeclPtrTy TagD = ActOnTag(S, TagSpec, Action::TK_Reference,
Douglas Gregor84a20812009-07-22 23:48:44 +00002829 KWLoc, SS, Name, NameLoc, Attr, AS_none,
2830 MultiTemplateParamsArg(*this, 0, 0), Owned);
Douglas Gregor96b6df92009-05-14 00:28:11 +00002831 if (!TagD)
2832 return true;
2833
2834 TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
2835 if (Tag->isEnum()) {
2836 Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
2837 << Context.getTypeDeclType(Tag);
2838 return true;
2839 }
2840
Douglas Gregord769bfa2009-05-27 17:30:49 +00002841 if (Tag->isInvalidDecl())
2842 return true;
2843
Douglas Gregor96b6df92009-05-14 00:28:11 +00002844 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
2845 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
2846 if (!Pattern) {
2847 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
2848 << Context.getTypeDeclType(Record);
2849 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
2850 return true;
2851 }
2852
2853 // C++0x [temp.explicit]p2:
2854 // [...] An explicit instantiation shall appear in an enclosing
2855 // namespace of its template. [...]
2856 //
2857 // This is C++ DR 275.
2858 if (getLangOptions().CPlusPlus0x) {
Mike Stumpe127ae32009-05-16 07:39:55 +00002859 // FIXME: In C++98, we would like to turn these errors into warnings,
2860 // dependent on a -Wc++0x flag.
Douglas Gregor96b6df92009-05-14 00:28:11 +00002861 DeclContext *PatternContext
2862 = Pattern->getDeclContext()->getEnclosingNamespaceContext();
2863 if (!CurContext->Encloses(PatternContext)) {
2864 Diag(TemplateLoc, diag::err_explicit_instantiation_out_of_scope)
2865 << Record << cast<NamedDecl>(PatternContext) << SS.getRange();
2866 Diag(Pattern->getLocation(), diag::note_previous_declaration);
2867 }
2868 }
2869
Douglas Gregor96b6df92009-05-14 00:28:11 +00002870 if (!Record->getDefinition(Context)) {
2871 // If the class has a definition, instantiate it (and all of its
2872 // members, recursively).
2873 Pattern = cast_or_null<CXXRecordDecl>(Pattern->getDefinition(Context));
2874 if (Pattern && InstantiateClass(TemplateLoc, Record, Pattern,
Douglas Gregor5f62c5e2009-05-14 23:26:13 +00002875 getTemplateInstantiationArgs(Record),
Douglas Gregor96b6df92009-05-14 00:28:11 +00002876 /*ExplicitInstantiation=*/true))
2877 return true;
Douglas Gregorb12249d2009-05-18 17:01:57 +00002878 } else // Instantiate all of the members of class.
Douglas Gregor96b6df92009-05-14 00:28:11 +00002879 InstantiateClassMembers(TemplateLoc, Record,
Douglas Gregor5f62c5e2009-05-14 23:26:13 +00002880 getTemplateInstantiationArgs(Record));
Douglas Gregor96b6df92009-05-14 00:28:11 +00002881
Mike Stumpe127ae32009-05-16 07:39:55 +00002882 // FIXME: We don't have any representation for explicit instantiations of
2883 // member classes. Such a representation is not needed for compilation, but it
2884 // should be available for clients that want to see all of the declarations in
2885 // the source code.
Douglas Gregor96b6df92009-05-14 00:28:11 +00002886 return TagD;
2887}
2888
Douglas Gregord3022602009-03-27 23:10:48 +00002889Sema::TypeResult
2890Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
2891 const IdentifierInfo &II, SourceLocation IdLoc) {
2892 NestedNameSpecifier *NNS
2893 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
2894 if (!NNS)
2895 return true;
2896
2897 QualType T = CheckTypenameType(NNS, II, SourceRange(TypenameLoc, IdLoc));
Douglas Gregord7cb0372009-04-01 21:51:26 +00002898 if (T.isNull())
2899 return true;
Douglas Gregord3022602009-03-27 23:10:48 +00002900 return T.getAsOpaquePtr();
2901}
2902
Douglas Gregor77da5802009-04-01 00:28:59 +00002903Sema::TypeResult
2904Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
2905 SourceLocation TemplateLoc, TypeTy *Ty) {
2906 QualType T = QualType::getFromOpaquePtr(Ty);
2907 NestedNameSpecifier *NNS
2908 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
2909 const TemplateSpecializationType *TemplateId
2910 = T->getAsTemplateSpecializationType();
2911 assert(TemplateId && "Expected a template specialization type");
2912
2913 if (NNS->isDependent())
2914 return Context.getTypenameType(NNS, TemplateId).getAsOpaquePtr();
2915
2916 return Context.getQualifiedNameType(NNS, T).getAsOpaquePtr();
2917}
2918
Douglas Gregord3022602009-03-27 23:10:48 +00002919/// \brief Build the type that describes a C++ typename specifier,
2920/// e.g., "typename T::type".
2921QualType
2922Sema::CheckTypenameType(NestedNameSpecifier *NNS, const IdentifierInfo &II,
2923 SourceRange Range) {
Douglas Gregor3eb20702009-05-11 19:58:34 +00002924 CXXRecordDecl *CurrentInstantiation = 0;
2925 if (NNS->isDependent()) {
2926 CurrentInstantiation = getCurrentInstantiationOf(NNS);
Douglas Gregord3022602009-03-27 23:10:48 +00002927
Douglas Gregor3eb20702009-05-11 19:58:34 +00002928 // If the nested-name-specifier does not refer to the current
2929 // instantiation, then build a typename type.
2930 if (!CurrentInstantiation)
2931 return Context.getTypenameType(NNS, &II);
2932 }
Douglas Gregord3022602009-03-27 23:10:48 +00002933
Douglas Gregor3eb20702009-05-11 19:58:34 +00002934 DeclContext *Ctx = 0;
2935
2936 if (CurrentInstantiation)
2937 Ctx = CurrentInstantiation;
2938 else {
2939 CXXScopeSpec SS;
2940 SS.setScopeRep(NNS);
2941 SS.setRange(Range);
2942 if (RequireCompleteDeclContext(SS))
2943 return QualType();
2944
2945 Ctx = computeDeclContext(SS);
2946 }
Douglas Gregord3022602009-03-27 23:10:48 +00002947 assert(Ctx && "No declaration context?");
2948
2949 DeclarationName Name(&II);
2950 LookupResult Result = LookupQualifiedName(Ctx, Name, LookupOrdinaryName,
2951 false);
2952 unsigned DiagID = 0;
2953 Decl *Referenced = 0;
2954 switch (Result.getKind()) {
2955 case LookupResult::NotFound:
2956 if (Ctx->isTranslationUnit())
2957 DiagID = diag::err_typename_nested_not_found_global;
2958 else
2959 DiagID = diag::err_typename_nested_not_found;
2960 break;
2961
2962 case LookupResult::Found:
2963 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getAsDecl())) {
2964 // We found a type. Build a QualifiedNameType, since the
2965 // typename-specifier was just sugar. FIXME: Tell
2966 // QualifiedNameType that it has a "typename" prefix.
2967 return Context.getQualifiedNameType(NNS, Context.getTypeDeclType(Type));
2968 }
2969
2970 DiagID = diag::err_typename_nested_not_type;
2971 Referenced = Result.getAsDecl();
2972 break;
2973
2974 case LookupResult::FoundOverloaded:
2975 DiagID = diag::err_typename_nested_not_type;
2976 Referenced = *Result.begin();
2977 break;
2978
2979 case LookupResult::AmbiguousBaseSubobjectTypes:
2980 case LookupResult::AmbiguousBaseSubobjects:
2981 case LookupResult::AmbiguousReference:
2982 DiagnoseAmbiguousLookup(Result, Name, Range.getEnd(), Range);
2983 return QualType();
2984 }
2985
2986 // If we get here, it's because name lookup did not find a
2987 // type. Emit an appropriate diagnostic and return an error.
2988 if (NamedDecl *NamedCtx = dyn_cast<NamedDecl>(Ctx))
2989 Diag(Range.getEnd(), DiagID) << Range << Name << NamedCtx;
2990 else
2991 Diag(Range.getEnd(), DiagID) << Range << Name;
2992 if (Referenced)
2993 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
2994 << Name;
2995 return QualType();
2996}