blob: f27d551d102135bcaed031c710e5c9b4a77578e0 [file] [log] [blame]
Douglas Gregor72c3f312008-12-05 18:15:24 +00001//===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===/
2
3//
4// The LLVM Compiler Infrastructure
5//
6// This file is distributed under the University of Illinois Open Source
7// License. See LICENSE.TXT for details.
Douglas Gregor99ebf652009-02-27 19:31:52 +00008//===----------------------------------------------------------------------===/
Douglas Gregor72c3f312008-12-05 18:15:24 +00009
10//
11// This file implements semantic analysis for C++ templates.
Douglas Gregor99ebf652009-02-27 19:31:52 +000012//===----------------------------------------------------------------------===/
Douglas Gregor72c3f312008-12-05 18:15:24 +000013
14#include "Sema.h"
Douglas Gregorddc29e12009-02-06 22:42:48 +000015#include "clang/AST/ASTContext.h"
Douglas Gregor898574e2008-12-05 23:32:09 +000016#include "clang/AST/Expr.h"
Douglas Gregorcc45cb32009-02-11 19:52:55 +000017#include "clang/AST/ExprCXX.h"
Douglas Gregoraaba5e32009-02-04 19:02:06 +000018#include "clang/AST/DeclTemplate.h"
Douglas Gregor72c3f312008-12-05 18:15:24 +000019#include "clang/Parse/DeclSpec.h"
20#include "clang/Basic/LangOptions.h"
21
22using namespace clang;
23
Douglas Gregord6fb7ef2008-12-18 19:37:40 +000024/// isTemplateName - Determines whether the identifier II is a
25/// template name in the current scope, and returns the template
26/// declaration if II names a template. An optional CXXScope can be
27/// passed to indicate the C++ scope in which the identifier will be
28/// found.
Douglas Gregorc45c2322009-03-31 00:43:58 +000029TemplateNameKind Sema::isTemplateName(const IdentifierInfo &II, Scope *S,
Douglas Gregor7532dc62009-03-30 22:58:21 +000030 TemplateTy &TemplateResult,
Douglas Gregor39a8de12009-02-25 19:37:18 +000031 const CXXScopeSpec *SS) {
Douglas Gregor47b9a1c2009-02-04 17:27:36 +000032 NamedDecl *IIDecl = LookupParsedName(S, SS, &II, LookupOrdinaryName);
Douglas Gregord6fb7ef2008-12-18 19:37:40 +000033
Douglas Gregor7532dc62009-03-30 22:58:21 +000034 TemplateNameKind TNK = TNK_Non_template;
35 TemplateDecl *Template = 0;
36
Douglas Gregord6fb7ef2008-12-18 19:37:40 +000037 if (IIDecl) {
Douglas Gregor7532dc62009-03-30 22:58:21 +000038 if ((Template = dyn_cast<TemplateDecl>(IIDecl))) {
Douglas Gregor55f6b142009-02-09 18:46:07 +000039 if (isa<FunctionTemplateDecl>(IIDecl))
Douglas Gregor7532dc62009-03-30 22:58:21 +000040 TNK = TNK_Function_template;
Douglas Gregorc45c2322009-03-31 00:43:58 +000041 else if (isa<ClassTemplateDecl>(IIDecl) ||
42 isa<TemplateTemplateParmDecl>(IIDecl))
43 TNK = TNK_Type_template;
Douglas Gregor7532dc62009-03-30 22:58:21 +000044 else
45 assert(false && "Unknown template declaration kind");
Douglas Gregorbefc20e2009-03-26 00:10:35 +000046 } else if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(IIDecl)) {
47 // C++ [temp.local]p1:
48 // Like normal (non-template) classes, class templates have an
49 // injected-class-name (Clause 9). The injected-class-name
50 // can be used with or without a template-argument-list. When
51 // it is used without a template-argument-list, it is
52 // equivalent to the injected-class-name followed by the
53 // template-parameters of the class template enclosed in
54 // <>. When it is used with a template-argument-list, it
55 // refers to the specified class template specialization,
56 // which could be the current specialization or another
57 // specialization.
58 if (Record->isInjectedClassName()) {
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +000059 Record = cast<CXXRecordDecl>(Record->getCanonicalDecl());
Douglas Gregor7532dc62009-03-30 22:58:21 +000060 if ((Template = Record->getDescribedClassTemplate()))
Douglas Gregorc45c2322009-03-31 00:43:58 +000061 TNK = TNK_Type_template;
Douglas Gregor7532dc62009-03-30 22:58:21 +000062 else if (ClassTemplateSpecializationDecl *Spec
Douglas Gregorbefc20e2009-03-26 00:10:35 +000063 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
Douglas Gregor7532dc62009-03-30 22:58:21 +000064 Template = Spec->getSpecializedTemplate();
Douglas Gregorc45c2322009-03-31 00:43:58 +000065 TNK = TNK_Type_template;
Douglas Gregorbefc20e2009-03-26 00:10:35 +000066 }
67 }
Douglas Gregor55f6b142009-02-09 18:46:07 +000068 }
Douglas Gregoraaba5e32009-02-04 19:02:06 +000069
Douglas Gregorc5c903a2009-06-24 00:23:40 +000070 // FIXME: What follows is a slightly less gross hack than what used to
71 // follow.
Douglas Gregord6fb7ef2008-12-18 19:37:40 +000072 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(IIDecl)) {
Douglas Gregorc5c903a2009-06-24 00:23:40 +000073 if (FD->getDescribedFunctionTemplate()) {
Douglas Gregor7532dc62009-03-30 22:58:21 +000074 TemplateResult = TemplateTy::make(FD);
Douglas Gregor55f6b142009-02-09 18:46:07 +000075 return TNK_Function_template;
76 }
Douglas Gregord6fb7ef2008-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 Gregore53060f2009-06-25 22:08:12 +000082 if (isa<FunctionTemplateDecl>(*F)) {
Douglas Gregor7532dc62009-03-30 22:58:21 +000083 TemplateResult = TemplateTy::make(Ovl);
Douglas Gregor55f6b142009-02-09 18:46:07 +000084 return TNK_Function_template;
85 }
Douglas Gregord6fb7ef2008-12-18 19:37:40 +000086 }
87 }
Douglas Gregor7532dc62009-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 Gregord6fb7ef2008-12-18 19:37:40 +0000100 }
Douglas Gregor7532dc62009-03-30 22:58:21 +0000101 return TNK;
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000102}
103
Douglas Gregor72c3f312008-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 Gregorf57172b2008-12-08 18:40:42 +0000109 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregor72c3f312008-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 Gregor2943aed2009-03-03 04:44:36 +0000124/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregoraaba5e32009-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 Lattnerb28317a2009-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 Gregoraaba5e32009-02-04 19:02:06 +0000130 return Temp;
131 }
132 return 0;
133}
134
Douglas Gregor72c3f312008-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 Carlsson941df7d2009-06-12 19:58:00 +0000144Sema::DeclPtrTy Sema::ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis,
145 SourceLocation EllipsisLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +0000146 SourceLocation KeyLoc,
147 IdentifierInfo *ParamName,
148 SourceLocation ParamNameLoc,
149 unsigned Depth, unsigned Position) {
Douglas Gregor72c3f312008-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 Gregor47b9a1c2009-02-04 17:27:36 +0000155 NamedDecl *PrevDecl = LookupName(S, ParamName, LookupTagName);
Douglas Gregorf57172b2008-12-08 18:40:42 +0000156 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor72c3f312008-12-05 18:15:24 +0000157 Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc,
158 PrevDecl);
159 }
160
Douglas Gregorddc29e12009-02-06 22:42:48 +0000161 SourceLocation Loc = ParamNameLoc;
162 if (!ParamName)
163 Loc = KeyLoc;
164
Douglas Gregor72c3f312008-12-05 18:15:24 +0000165 TemplateTypeParmDecl *Param
Douglas Gregorddc29e12009-02-06 22:42:48 +0000166 = TemplateTypeParmDecl::Create(Context, CurContext, Loc,
Anders Carlsson6d845ae2009-06-12 22:23:22 +0000167 Depth, Position, ParamName, Typename,
168 Ellipsis);
Douglas Gregor72c3f312008-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 Lattnerb28317a2009-03-28 19:18:32 +0000174 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor72c3f312008-12-05 18:15:24 +0000175 IdResolver.AddDecl(Param);
176 }
177
Chris Lattnerb28317a2009-03-28 19:18:32 +0000178 return DeclPtrTy::make(Param);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000179}
180
Douglas Gregord684b002009-02-10 19:49:53 +0000181/// ActOnTypeParameterDefault - Adds a default argument (the type
182/// Default) to the given template type parameter (TypeParam).
Chris Lattnerb28317a2009-03-28 19:18:32 +0000183void Sema::ActOnTypeParameterDefault(DeclPtrTy TypeParam,
Douglas Gregord684b002009-02-10 19:49:53 +0000184 SourceLocation EqualLoc,
185 SourceLocation DefaultLoc,
186 TypeTy *DefaultT) {
187 TemplateTypeParmDecl *Parm
Chris Lattnerb28317a2009-03-28 19:18:32 +0000188 = cast<TemplateTypeParmDecl>(TypeParam.getAs<Decl>());
Douglas Gregord684b002009-02-10 19:49:53 +0000189 QualType Default = QualType::getFromOpaquePtr(DefaultT);
190
Anders Carlsson9c4c5c82009-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 Carlsson9c4c5c82009-06-12 22:30:13 +0000196 return;
197 }
198
Douglas Gregord684b002009-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 Gregor2943aed2009-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 Kremenek35366a62009-07-17 17:50:17 +0000228 (T->getAsPointerType()->getPointeeType()->isObjectType() ||
229 T->getAsPointerType()->getPointeeType()->isFunctionType())) ||
Douglas Gregor2943aed2009-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 Gregor72c3f312008-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 Lattnerb28317a2009-03-28 19:18:32 +0000260Sema::DeclPtrTy Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
261 unsigned Depth,
262 unsigned Position) {
Douglas Gregor72c3f312008-12-05 18:15:24 +0000263 QualType T = GetTypeForDeclarator(D, S);
264
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000265 assert(S->isTemplateParamScope() &&
266 "Non-type template parameter not in template parameter scope!");
Douglas Gregor72c3f312008-12-05 18:15:24 +0000267 bool Invalid = false;
268
269 IdentifierInfo *ParamName = D.getIdentifier();
270 if (ParamName) {
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000271 NamedDecl *PrevDecl = LookupName(S, ParamName, LookupTagName);
Douglas Gregorf57172b2008-12-08 18:40:42 +0000272 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor72c3f312008-12-05 18:15:24 +0000273 Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000274 PrevDecl);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000275 }
276
Douglas Gregor2943aed2009-03-03 04:44:36 +0000277 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
Douglas Gregorceef30c2009-03-09 16:46:39 +0000278 if (T.isNull()) {
Douglas Gregor2943aed2009-03-03 04:44:36 +0000279 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregorceef30c2009-03-09 16:46:39 +0000280 Invalid = true;
281 }
Douglas Gregor5d290d52009-02-10 17:43:50 +0000282
Douglas Gregor72c3f312008-12-05 18:15:24 +0000283 NonTypeTemplateParmDecl *Param
284 = NonTypeTemplateParmDecl::Create(Context, CurContext, D.getIdentifierLoc(),
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000285 Depth, Position, ParamName, T);
Douglas Gregor72c3f312008-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 Lattnerb28317a2009-03-28 19:18:32 +0000291 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor72c3f312008-12-05 18:15:24 +0000292 IdResolver.AddDecl(Param);
293 }
Chris Lattnerb28317a2009-03-28 19:18:32 +0000294 return DeclPtrTy::make(Param);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000295}
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000296
Douglas Gregord684b002009-02-10 19:49:53 +0000297/// \brief Adds a default argument to the given non-type template
298/// parameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000299void Sema::ActOnNonTypeTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregord684b002009-02-10 19:49:53 +0000300 SourceLocation EqualLoc,
301 ExprArg DefaultE) {
302 NonTypeTemplateParmDecl *TemplateParm
Chris Lattnerb28317a2009-03-28 19:18:32 +0000303 = cast<NonTypeTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregord684b002009-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 Gregor02cbbd22009-06-11 18:10:32 +0000311 TemplateArgument Converted;
312 if (CheckTemplateArgument(TemplateParm, TemplateParm->getType(), Default,
313 Converted)) {
Douglas Gregord684b002009-02-10 19:49:53 +0000314 TemplateParm->setInvalidDecl();
315 return;
316 }
317
Anders Carlssone9146f22009-05-01 19:49:17 +0000318 TemplateParm->setDefaultArgument(DefaultE.takeAs<Expr>());
Douglas Gregord684b002009-02-10 19:49:53 +0000319}
320
Douglas Gregoraaba5e32009-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 Lattnerb28317a2009-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 Gregoraaba5e32009-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 Lattnerb28317a2009-03-28 19:18:32 +0000354 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000355 IdResolver.AddDecl(Param);
356 }
357
Chris Lattnerb28317a2009-03-28 19:18:32 +0000358 return DeclPtrTy::make(Param);
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000359}
360
Douglas Gregord684b002009-02-10 19:49:53 +0000361/// \brief Adds a default argument to the given template template
362/// parameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000363void Sema::ActOnTemplateTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregord684b002009-02-10 19:49:53 +0000364 SourceLocation EqualLoc,
365 ExprArg DefaultE) {
366 TemplateTemplateParmDecl *TemplateParm
Chris Lattnerb28317a2009-03-28 19:18:32 +0000367 = cast<TemplateTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregord684b002009-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 Gregorc4b4e7b2008-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 Lattnerb28317a2009-03-28 19:18:32 +0000402 DeclPtrTy *Params, unsigned NumParams,
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000403 SourceLocation RAngleLoc) {
404 if (ExportLoc.isValid())
405 Diag(ExportLoc, diag::note_template_export_unsupported);
406
Douglas Gregorddc29e12009-02-06 22:42:48 +0000407 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
408 (Decl**)Params, NumParams, RAngleLoc);
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000409}
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000410
Douglas Gregor212e81c2009-03-25 00:13:59 +0000411Sema::DeclResult
Douglas Gregorbd1099e2009-07-23 16:36:45 +0000412Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagKind TK,
Douglas Gregorddc29e12009-02-06 22:42:48 +0000413 SourceLocation KWLoc, const CXXScopeSpec &SS,
414 IdentifierInfo *Name, SourceLocation NameLoc,
415 AttributeList *Attr,
Anders Carlsson5aeccdb2009-03-26 00:52:18 +0000416 MultiTemplateParamsArg TemplateParameterLists,
417 AccessSpecifier AS) {
Douglas Gregorddc29e12009-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 Gregord684b002009-02-10 19:49:53 +0000420 bool Invalid = false;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000421
422 // Check that we can declare a template here.
423 if (CheckTemplateDeclScope(S, TemplateParameterLists))
Douglas Gregor212e81c2009-03-25 00:13:59 +0000424 return true;
Douglas Gregorddc29e12009-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 Gregor212e81c2009-03-25 00:13:59 +0000437 return true;
Douglas Gregorddc29e12009-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 Gregorc19ee3e2009-06-17 23:37:01 +0000448 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
449 PrevDecl = 0;
450
Douglas Gregorddc29e12009-02-06 22:42:48 +0000451 DeclContext *SemanticContext = CurContext;
452 if (SS.isNotEmpty() && !SS.isInvalid()) {
Douglas Gregore4e5b052009-03-19 00:18:19 +0000453 SemanticContext = computeDeclContext(SS);
Douglas Gregorddc29e12009-02-06 22:42:48 +0000454
Mike Stump390b4cc2009-05-16 07:39:55 +0000455 // FIXME: need to match up several levels of template parameter lists here.
Douglas Gregorddc29e12009-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 Gregor212e81c2009-03-25 00:13:59 +0000471 return true;
Douglas Gregorddc29e12009-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 Gregor501c5ce2009-05-14 16:41:31 +0000479 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind, KWLoc, *Name)) {
Douglas Gregora3a83512009-04-01 23:51:29 +0000480 Diag(KWLoc, diag::err_use_with_wrong_tag)
481 << Name
482 << CodeModificationHint::CreateReplacement(KWLoc,
483 PrevRecordDecl->getKindName());
Douglas Gregorddc29e12009-02-06 22:42:48 +0000484 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregora3a83512009-04-01 23:51:29 +0000485 Kind = PrevRecordDecl->getTagKind();
Douglas Gregorddc29e12009-02-06 22:42:48 +0000486 }
487
Douglas Gregorddc29e12009-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 Gregor212e81c2009-03-25 00:13:59 +0000495 return true;
Douglas Gregorddc29e12009-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 Gregor212e81c2009-03-25 00:13:59 +0000511 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000512 }
513
Douglas Gregord684b002009-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 Gregor7da97d02009-05-10 22:57:19 +0000521 // FIXME: If we had a scope specifier, we better have a previous template
Douglas Gregorddc29e12009-02-06 22:42:48 +0000522 // declaration!
523
Douglas Gregorbefc20e2009-03-26 00:10:35 +0000524 CXXRecordDecl *NewClass =
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000525 CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name, KWLoc,
Douglas Gregorddc29e12009-02-06 22:42:48 +0000526 PrevClassTemplate?
Douglas Gregoraafc0cc2009-05-15 19:11:46 +0000527 PrevClassTemplate->getTemplatedDecl() : 0,
528 /*DelayTypeCreation=*/true);
Douglas Gregorddc29e12009-02-06 22:42:48 +0000529
530 ClassTemplateDecl *NewTemplate
531 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
532 DeclarationName(Name), TemplateParams,
Douglas Gregor5953d8b2009-03-19 17:26:29 +0000533 NewClass, PrevClassTemplate);
Douglas Gregorbefc20e2009-03-26 00:10:35 +0000534 NewClass->setDescribedClassTemplate(NewTemplate);
535
Douglas Gregoraafc0cc2009-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 Carlsson4cbe82c2009-03-26 01:24:28 +0000544 // Set the access specifier.
545 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
546
Douglas Gregorddc29e12009-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 Gregor9cdda0c2009-06-17 21:51:59 +0000555 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregorddc29e12009-02-06 22:42:48 +0000556
557 PushOnScopeChains(NewTemplate, S);
558
Douglas Gregord684b002009-02-10 19:49:53 +0000559 if (Invalid) {
560 NewTemplate->setInvalidDecl();
561 NewClass->setInvalidDecl();
562 }
Chris Lattnerb28317a2009-03-28 19:18:32 +0000563 return DeclPtrTy::make(NewTemplate);
Douglas Gregorddc29e12009-02-06 22:42:48 +0000564}
565
Douglas Gregord684b002009-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 Gregorc15cb382009-02-09 23:23:08 +0000597
Anders Carlsson49d25572009-06-12 23:20:15 +0000598 bool SawParameterPack = false;
599 SourceLocation ParameterPackLoc;
600
Mike Stump1a35fde2009-02-11 23:03:27 +0000601 // Dummy initialization to avoid warnings.
Douglas Gregor1bc69132009-02-11 20:46:19 +0000602 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregord684b002009-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 Carlsson49d25572009-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 Gregord684b002009-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 Carlsson49d25572009-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 Gregord684b002009-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 Stump390b4cc2009-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 Gregord684b002009-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 Gregorc15cb382009-02-09 23:23:08 +0000741
Douglas Gregorf59a56e2009-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 Gregor40808ce2009-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 Gregor7532dc62009-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 Gregorc45c2322009-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 Gregorc45c2322009-03-31 00:43:58 +0000887 return Context.getTemplateSpecializationType(Name, TemplateArgs,
Douglas Gregor1275ae02009-07-28 23:00:59 +0000888 NumTemplateArgs);
Douglas Gregorc45c2322009-03-31 00:43:58 +0000889 }
Douglas Gregor7532dc62009-03-30 22:58:21 +0000890
Douglas Gregor40808ce2009-03-09 23:48:35 +0000891 // Check that the template argument list is well-formed for this
892 // template.
Anders Carlssonfb250522009-06-23 01:26:57 +0000893 TemplateArgumentListBuilder Converted(Template->getTemplateParameters(),
894 NumTemplateArgs);
Douglas Gregor7532dc62009-03-30 22:58:21 +0000895 if (CheckTemplateArgumentList(Template, TemplateLoc, LAngleLoc,
Douglas Gregor40808ce2009-03-09 23:48:35 +0000896 TemplateArgs, NumTemplateArgs, RAngleLoc,
Douglas Gregor16134c62009-07-01 00:28:38 +0000897 false, Converted))
Douglas Gregor40808ce2009-03-09 23:48:35 +0000898 return QualType();
899
Anders Carlssonfb250522009-06-23 01:26:57 +0000900 assert((Converted.structuredSize() ==
Douglas Gregor7532dc62009-03-30 22:58:21 +0000901 Template->getTemplateParameters()->size()) &&
Douglas Gregor40808ce2009-03-09 23:48:35 +0000902 "Converted template argument list is too short!");
903
904 QualType CanonType;
905
Douglas Gregor7532dc62009-03-30 22:58:21 +0000906 if (TemplateSpecializationType::anyDependentTemplateArguments(
Douglas Gregor40808ce2009-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 Gregor25a3ef72009-05-07 06:41:52 +0000916 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
917 CanonType = Context.getTemplateSpecializationType(CanonName,
Anders Carlssonfb250522009-06-23 01:26:57 +0000918 Converted.getFlatArguments(),
919 Converted.flatSize());
Douglas Gregor1275ae02009-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 Gregor7532dc62009-03-30 22:58:21 +0000926 } else if (ClassTemplateDecl *ClassTemplate
927 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregor40808ce2009-03-09 23:48:35 +0000928 // Find the class template specialization declaration that
929 // corresponds to these arguments.
930 llvm::FoldingSetNodeID ID;
Anders Carlsson1c5976e2009-06-05 03:43:12 +0000931 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlssonfb250522009-06-23 01:26:57 +0000932 Converted.getFlatArguments(),
Douglas Gregor828e2262009-07-29 16:09:57 +0000933 Converted.flatSize(),
934 Context);
Douglas Gregor40808ce2009-03-09 23:48:35 +0000935 void *InsertPos = 0;
936 ClassTemplateSpecializationDecl *Decl
937 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
938 if (!Decl) {
939 // This is the first time we have referenced this class template
940 // specialization. Create the canonical declaration and add it to
941 // the set of specializations.
942 Decl = ClassTemplateSpecializationDecl::Create(Context,
Anders Carlsson1c5976e2009-06-05 03:43:12 +0000943 ClassTemplate->getDeclContext(),
944 TemplateLoc,
945 ClassTemplate,
Anders Carlssonfb250522009-06-23 01:26:57 +0000946 Converted, 0);
Douglas Gregor40808ce2009-03-09 23:48:35 +0000947 ClassTemplate->getSpecializations().InsertNode(Decl, InsertPos);
948 Decl->setLexicalDeclContext(CurContext);
949 }
950
951 CanonType = Context.getTypeDeclType(Decl);
952 }
953
954 // Build the fully-sugared type for this class template
955 // specialization, which refers back to the class template
956 // specialization we created or found.
Douglas Gregor7532dc62009-03-30 22:58:21 +0000957 return Context.getTemplateSpecializationType(Name, TemplateArgs,
958 NumTemplateArgs, CanonType);
Douglas Gregor40808ce2009-03-09 23:48:35 +0000959}
960
Douglas Gregorcc636682009-02-17 23:15:12 +0000961Action::TypeResult
Douglas Gregor7532dc62009-03-30 22:58:21 +0000962Sema::ActOnTemplateIdType(TemplateTy TemplateD, SourceLocation TemplateLoc,
963 SourceLocation LAngleLoc,
964 ASTTemplateArgsPtr TemplateArgsIn,
965 SourceLocation *TemplateArgLocs,
966 SourceLocation RAngleLoc) {
967 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Douglas Gregor55f6b142009-02-09 18:46:07 +0000968
Douglas Gregor40808ce2009-03-09 23:48:35 +0000969 // Translate the parser's template argument list in our AST format.
970 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
971 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
Douglas Gregorc15cb382009-02-09 23:23:08 +0000972
Douglas Gregor7532dc62009-03-30 22:58:21 +0000973 QualType Result = CheckTemplateIdType(Template, TemplateLoc, LAngleLoc,
Jay Foadbeaaccd2009-05-21 09:52:38 +0000974 TemplateArgs.data(),
975 TemplateArgs.size(),
Douglas Gregor7532dc62009-03-30 22:58:21 +0000976 RAngleLoc);
Douglas Gregor40808ce2009-03-09 23:48:35 +0000977 TemplateArgsIn.release();
Douglas Gregor31a19b62009-04-01 21:51:26 +0000978
979 if (Result.isNull())
980 return true;
981
Douglas Gregor5908e9f2009-02-09 19:34:22 +0000982 return Result.getAsOpaquePtr();
Douglas Gregor55f6b142009-02-09 18:46:07 +0000983}
984
Douglas Gregoredce4dd2009-06-30 22:34:41 +0000985Sema::OwningExprResult Sema::BuildTemplateIdExpr(TemplateName Template,
986 SourceLocation TemplateNameLoc,
987 SourceLocation LAngleLoc,
988 const TemplateArgument *TemplateArgs,
989 unsigned NumTemplateArgs,
990 SourceLocation RAngleLoc) {
991 // FIXME: Can we do any checking at this point? I guess we could check the
992 // template arguments that we have against the template name, if the template
993 // name refers to a single template. That's not a terribly common case,
994 // though.
995 return Owned(TemplateIdRefExpr::Create(Context,
996 /*FIXME: New type?*/Context.OverloadTy,
997 /*FIXME: Necessary?*/0,
998 /*FIXME: Necessary?*/SourceRange(),
999 Template, TemplateNameLoc, LAngleLoc,
1000 TemplateArgs,
1001 NumTemplateArgs, RAngleLoc));
1002}
1003
1004Sema::OwningExprResult Sema::ActOnTemplateIdExpr(TemplateTy TemplateD,
1005 SourceLocation TemplateNameLoc,
1006 SourceLocation LAngleLoc,
1007 ASTTemplateArgsPtr TemplateArgsIn,
1008 SourceLocation *TemplateArgLocs,
1009 SourceLocation RAngleLoc) {
1010 TemplateName Template = TemplateD.getAsVal<TemplateName>();
1011
1012 // Translate the parser's template argument list in our AST format.
1013 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
1014 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001015 TemplateArgsIn.release();
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001016
1017 return BuildTemplateIdExpr(Template, TemplateNameLoc, LAngleLoc,
1018 TemplateArgs.data(), TemplateArgs.size(),
1019 RAngleLoc);
1020}
1021
Douglas Gregorc45c2322009-03-31 00:43:58 +00001022/// \brief Form a dependent template name.
1023///
1024/// This action forms a dependent template name given the template
1025/// name and its (presumably dependent) scope specifier. For
1026/// example, given "MetaFun::template apply", the scope specifier \p
1027/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
1028/// of the "template" keyword, and "apply" is the \p Name.
1029Sema::TemplateTy
1030Sema::ActOnDependentTemplateName(SourceLocation TemplateKWLoc,
1031 const IdentifierInfo &Name,
1032 SourceLocation NameLoc,
1033 const CXXScopeSpec &SS) {
1034 if (!SS.isSet() || SS.isInvalid())
1035 return TemplateTy();
1036
1037 NestedNameSpecifier *Qualifier
1038 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
1039
1040 // FIXME: member of the current instantiation
1041
1042 if (!Qualifier->isDependent()) {
1043 // C++0x [temp.names]p5:
1044 // If a name prefixed by the keyword template is not the name of
1045 // a template, the program is ill-formed. [Note: the keyword
1046 // template may not be applied to non-template members of class
1047 // templates. -end note ] [ Note: as is the case with the
1048 // typename prefix, the template prefix is allowed in cases
1049 // where it is not strictly necessary; i.e., when the
1050 // nested-name-specifier or the expression on the left of the ->
1051 // or . is not dependent on a template-parameter, or the use
1052 // does not appear in the scope of a template. -end note]
1053 //
1054 // Note: C++03 was more strict here, because it banned the use of
1055 // the "template" keyword prior to a template-name that was not a
1056 // dependent name. C++ DR468 relaxed this requirement (the
1057 // "template" keyword is now permitted). We follow the C++0x
1058 // rules, even in C++03 mode, retroactively applying the DR.
1059 TemplateTy Template;
1060 TemplateNameKind TNK = isTemplateName(Name, 0, Template, &SS);
1061 if (TNK == TNK_Non_template) {
1062 Diag(NameLoc, diag::err_template_kw_refers_to_non_template)
1063 << &Name;
1064 return TemplateTy();
1065 }
1066
1067 return Template;
1068 }
1069
1070 return TemplateTy::make(Context.getDependentTemplateName(Qualifier, &Name));
1071}
1072
Anders Carlsson436b1562009-06-13 00:33:33 +00001073bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
1074 const TemplateArgument &Arg,
1075 TemplateArgumentListBuilder &Converted) {
1076 // Check template type parameter.
1077 if (Arg.getKind() != TemplateArgument::Type) {
1078 // C++ [temp.arg.type]p1:
1079 // A template-argument for a template-parameter which is a
1080 // type shall be a type-id.
1081
1082 // We have a template type parameter but the template argument
1083 // is not a type.
1084 Diag(Arg.getLocation(), diag::err_template_arg_must_be_type);
1085 Diag(Param->getLocation(), diag::note_template_param_here);
1086
1087 return true;
1088 }
1089
1090 if (CheckTemplateArgument(Param, Arg.getAsType(), Arg.getLocation()))
1091 return true;
1092
1093 // Add the converted template type argument.
Anders Carlssonfb250522009-06-23 01:26:57 +00001094 Converted.Append(
Anders Carlsson436b1562009-06-13 00:33:33 +00001095 TemplateArgument(Arg.getLocation(),
1096 Context.getCanonicalType(Arg.getAsType())));
1097 return false;
1098}
1099
Douglas Gregorc15cb382009-02-09 23:23:08 +00001100/// \brief Check that the given template argument list is well-formed
1101/// for specializing the given template.
1102bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
1103 SourceLocation TemplateLoc,
1104 SourceLocation LAngleLoc,
Douglas Gregor40808ce2009-03-09 23:48:35 +00001105 const TemplateArgument *TemplateArgs,
1106 unsigned NumTemplateArgs,
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001107 SourceLocation RAngleLoc,
Douglas Gregor16134c62009-07-01 00:28:38 +00001108 bool PartialTemplateArgs,
Anders Carlsson1c5976e2009-06-05 03:43:12 +00001109 TemplateArgumentListBuilder &Converted) {
Douglas Gregorc15cb382009-02-09 23:23:08 +00001110 TemplateParameterList *Params = Template->getTemplateParameters();
1111 unsigned NumParams = Params->size();
Douglas Gregor40808ce2009-03-09 23:48:35 +00001112 unsigned NumArgs = NumTemplateArgs;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001113 bool Invalid = false;
1114
Anders Carlsson0ceffb52009-06-13 02:08:00 +00001115 bool HasParameterPack =
1116 NumParams > 0 && Params->getParam(NumParams - 1)->isTemplateParameterPack();
1117
1118 if ((NumArgs > NumParams && !HasParameterPack) ||
Douglas Gregor16134c62009-07-01 00:28:38 +00001119 (NumArgs < Params->getMinRequiredArguments() &&
1120 !PartialTemplateArgs)) {
Douglas Gregorc15cb382009-02-09 23:23:08 +00001121 // FIXME: point at either the first arg beyond what we can handle,
1122 // or the '>', depending on whether we have too many or too few
1123 // arguments.
1124 SourceRange Range;
1125 if (NumArgs > NumParams)
Douglas Gregor40808ce2009-03-09 23:48:35 +00001126 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
Douglas Gregorc15cb382009-02-09 23:23:08 +00001127 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
1128 << (NumArgs > NumParams)
1129 << (isa<ClassTemplateDecl>(Template)? 0 :
1130 isa<FunctionTemplateDecl>(Template)? 1 :
1131 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
1132 << Template << Range;
Douglas Gregor62cb18d2009-02-11 18:16:40 +00001133 Diag(Template->getLocation(), diag::note_template_decl_here)
1134 << Params->getSourceRange();
Douglas Gregorc15cb382009-02-09 23:23:08 +00001135 Invalid = true;
1136 }
1137
1138 // C++ [temp.arg]p1:
1139 // [...] The type and form of each template-argument specified in
1140 // a template-id shall match the type and form specified for the
1141 // corresponding parameter declared by the template in its
1142 // template-parameter-list.
1143 unsigned ArgIdx = 0;
1144 for (TemplateParameterList::iterator Param = Params->begin(),
1145 ParamEnd = Params->end();
1146 Param != ParamEnd; ++Param, ++ArgIdx) {
Douglas Gregor16134c62009-07-01 00:28:38 +00001147 if (ArgIdx > NumArgs && PartialTemplateArgs)
1148 break;
1149
Douglas Gregorc15cb382009-02-09 23:23:08 +00001150 // Decode the template argument
Douglas Gregor40808ce2009-03-09 23:48:35 +00001151 TemplateArgument Arg;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001152 if (ArgIdx >= NumArgs) {
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001153 // Retrieve the default template argument from the template
1154 // parameter.
1155 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
Anders Carlsson0ceffb52009-06-13 02:08:00 +00001156 if (TTP->isParameterPack()) {
Anders Carlssonfb250522009-06-23 01:26:57 +00001157 // We have an empty argument pack.
1158 Converted.BeginPack();
1159 Converted.EndPack();
Anders Carlsson0ceffb52009-06-13 02:08:00 +00001160 break;
1161 }
1162
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001163 if (!TTP->hasDefaultArgument())
1164 break;
1165
Douglas Gregor40808ce2009-03-09 23:48:35 +00001166 QualType ArgType = TTP->getDefaultArgument();
Douglas Gregor99ebf652009-02-27 19:31:52 +00001167
1168 // If the argument type is dependent, instantiate it now based
1169 // on the previously-computed template arguments.
Douglas Gregordf667e72009-03-10 20:44:00 +00001170 if (ArgType->isDependentType()) {
1171 InstantiatingTemplate Inst(*this, TemplateLoc,
Anders Carlssonfb250522009-06-23 01:26:57 +00001172 Template, Converted.getFlatArguments(),
Anders Carlsson1c5976e2009-06-05 03:43:12 +00001173 Converted.flatSize(),
Douglas Gregordf667e72009-03-10 20:44:00 +00001174 SourceRange(TemplateLoc, RAngleLoc));
Douglas Gregor7e063902009-05-11 23:53:27 +00001175
Anders Carlssone9c904b2009-06-05 04:47:51 +00001176 TemplateArgumentList TemplateArgs(Context, Converted,
Anders Carlssonfb250522009-06-23 01:26:57 +00001177 /*TakeArgs=*/false);
Douglas Gregor7e063902009-05-11 23:53:27 +00001178 ArgType = InstantiateType(ArgType, TemplateArgs,
Douglas Gregor99ebf652009-02-27 19:31:52 +00001179 TTP->getDefaultArgumentLoc(),
1180 TTP->getDeclName());
Douglas Gregordf667e72009-03-10 20:44:00 +00001181 }
Douglas Gregor99ebf652009-02-27 19:31:52 +00001182
1183 if (ArgType.isNull())
Douglas Gregorcd281c32009-02-28 00:25:32 +00001184 return true;
Douglas Gregor99ebf652009-02-27 19:31:52 +00001185
Douglas Gregor40808ce2009-03-09 23:48:35 +00001186 Arg = TemplateArgument(TTP->getLocation(), ArgType);
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001187 } else if (NonTypeTemplateParmDecl *NTTP
1188 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
1189 if (!NTTP->hasDefaultArgument())
1190 break;
1191
Anders Carlsson3b56c002009-06-11 16:06:49 +00001192 InstantiatingTemplate Inst(*this, TemplateLoc,
Anders Carlssonfb250522009-06-23 01:26:57 +00001193 Template, Converted.getFlatArguments(),
Anders Carlsson3b56c002009-06-11 16:06:49 +00001194 Converted.flatSize(),
1195 SourceRange(TemplateLoc, RAngleLoc));
1196
1197 TemplateArgumentList TemplateArgs(Context, Converted,
Anders Carlssonfb250522009-06-23 01:26:57 +00001198 /*TakeArgs=*/false);
Anders Carlsson3b56c002009-06-11 16:06:49 +00001199
1200 Sema::OwningExprResult E = InstantiateExpr(NTTP->getDefaultArgument(),
1201 TemplateArgs);
1202 if (E.isInvalid())
1203 return true;
1204
1205 Arg = TemplateArgument(E.takeAs<Expr>());
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001206 } else {
1207 TemplateTemplateParmDecl *TempParm
1208 = cast<TemplateTemplateParmDecl>(*Param);
1209
1210 if (!TempParm->hasDefaultArgument())
1211 break;
1212
Douglas Gregor2943aed2009-03-03 04:44:36 +00001213 // FIXME: Instantiate default argument
Douglas Gregor40808ce2009-03-09 23:48:35 +00001214 Arg = TemplateArgument(TempParm->getDefaultArgument());
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001215 }
1216 } else {
1217 // Retrieve the template argument produced by the user.
Douglas Gregor40808ce2009-03-09 23:48:35 +00001218 Arg = TemplateArgs[ArgIdx];
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001219 }
1220
Douglas Gregorc15cb382009-02-09 23:23:08 +00001221
1222 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
Anders Carlsson0ceffb52009-06-13 02:08:00 +00001223 if (TTP->isParameterPack()) {
Anders Carlssonfb250522009-06-23 01:26:57 +00001224 Converted.BeginPack();
Anders Carlsson0ceffb52009-06-13 02:08:00 +00001225 // Check all the remaining arguments (if any).
1226 for (; ArgIdx < NumArgs; ++ArgIdx) {
1227 if (CheckTemplateTypeArgument(TTP, TemplateArgs[ArgIdx], Converted))
1228 Invalid = true;
1229 }
1230
Anders Carlssonfb250522009-06-23 01:26:57 +00001231 Converted.EndPack();
Anders Carlsson0ceffb52009-06-13 02:08:00 +00001232 } else {
1233 if (CheckTemplateTypeArgument(TTP, Arg, Converted))
1234 Invalid = true;
1235 }
Douglas Gregorc15cb382009-02-09 23:23:08 +00001236 } else if (NonTypeTemplateParmDecl *NTTP
1237 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
1238 // Check non-type template parameters.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001239
1240 // Instantiate the type of the non-type template parameter with
1241 // the template arguments we've seen thus far.
1242 QualType NTTPType = NTTP->getType();
1243 if (NTTPType->isDependentType()) {
1244 // Instantiate the type of the non-type template parameter.
Douglas Gregordf667e72009-03-10 20:44:00 +00001245 InstantiatingTemplate Inst(*this, TemplateLoc,
Anders Carlssonfb250522009-06-23 01:26:57 +00001246 Template, Converted.getFlatArguments(),
Anders Carlsson1c5976e2009-06-05 03:43:12 +00001247 Converted.flatSize(),
Douglas Gregordf667e72009-03-10 20:44:00 +00001248 SourceRange(TemplateLoc, RAngleLoc));
1249
Anders Carlssone9c904b2009-06-05 04:47:51 +00001250 TemplateArgumentList TemplateArgs(Context, Converted,
Anders Carlssonfb250522009-06-23 01:26:57 +00001251 /*TakeArgs=*/false);
Douglas Gregor7e063902009-05-11 23:53:27 +00001252 NTTPType = InstantiateType(NTTPType, TemplateArgs,
Douglas Gregor2943aed2009-03-03 04:44:36 +00001253 NTTP->getLocation(),
1254 NTTP->getDeclName());
1255 // If that worked, check the non-type template parameter type
1256 // for validity.
1257 if (!NTTPType.isNull())
1258 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
1259 NTTP->getLocation());
Douglas Gregor2943aed2009-03-03 04:44:36 +00001260 if (NTTPType.isNull()) {
1261 Invalid = true;
1262 break;
1263 }
1264 }
1265
Douglas Gregor40808ce2009-03-09 23:48:35 +00001266 switch (Arg.getKind()) {
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001267 case TemplateArgument::Null:
1268 assert(false && "Should never see a NULL template argument here");
1269 break;
1270
Douglas Gregor40808ce2009-03-09 23:48:35 +00001271 case TemplateArgument::Expression: {
1272 Expr *E = Arg.getAsExpr();
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001273 TemplateArgument Result;
1274 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
Douglas Gregorc15cb382009-02-09 23:23:08 +00001275 Invalid = true;
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001276 else
Anders Carlssonfb250522009-06-23 01:26:57 +00001277 Converted.Append(Result);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001278 break;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001279 }
1280
Douglas Gregor40808ce2009-03-09 23:48:35 +00001281 case TemplateArgument::Declaration:
1282 case TemplateArgument::Integral:
1283 // We've already checked this template argument, so just copy
1284 // it to the list of converted arguments.
Anders Carlssonfb250522009-06-23 01:26:57 +00001285 Converted.Append(Arg);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001286 break;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001287
Douglas Gregor40808ce2009-03-09 23:48:35 +00001288 case TemplateArgument::Type:
1289 // We have a non-type template parameter but the template
1290 // argument is a type.
1291
1292 // C++ [temp.arg]p2:
1293 // In a template-argument, an ambiguity between a type-id and
1294 // an expression is resolved to a type-id, regardless of the
1295 // form of the corresponding template-parameter.
1296 //
1297 // We warn specifically about this case, since it can be rather
1298 // confusing for users.
1299 if (Arg.getAsType()->isFunctionType())
1300 Diag(Arg.getLocation(), diag::err_template_arg_nontype_ambig)
1301 << Arg.getAsType();
1302 else
1303 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr);
1304 Diag((*Param)->getLocation(), diag::note_template_param_here);
1305 Invalid = true;
Anders Carlssond01b1da2009-06-15 17:04:53 +00001306 break;
1307
1308 case TemplateArgument::Pack:
1309 assert(0 && "FIXME: Implement!");
1310 break;
Douglas Gregor40808ce2009-03-09 23:48:35 +00001311 }
Douglas Gregorc15cb382009-02-09 23:23:08 +00001312 } else {
1313 // Check template template parameters.
1314 TemplateTemplateParmDecl *TempParm
1315 = cast<TemplateTemplateParmDecl>(*Param);
1316
Douglas Gregor40808ce2009-03-09 23:48:35 +00001317 switch (Arg.getKind()) {
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001318 case TemplateArgument::Null:
1319 assert(false && "Should never see a NULL template argument here");
1320 break;
1321
Douglas Gregor40808ce2009-03-09 23:48:35 +00001322 case TemplateArgument::Expression: {
1323 Expr *ArgExpr = Arg.getAsExpr();
1324 if (ArgExpr && isa<DeclRefExpr>(ArgExpr) &&
1325 isa<TemplateDecl>(cast<DeclRefExpr>(ArgExpr)->getDecl())) {
1326 if (CheckTemplateArgument(TempParm, cast<DeclRefExpr>(ArgExpr)))
1327 Invalid = true;
1328
1329 // Add the converted template argument.
Douglas Gregor7da97d02009-05-10 22:57:19 +00001330 Decl *D
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00001331 = cast<DeclRefExpr>(ArgExpr)->getDecl()->getCanonicalDecl();
Anders Carlssonfb250522009-06-23 01:26:57 +00001332 Converted.Append(TemplateArgument(Arg.getLocation(), D));
Douglas Gregor40808ce2009-03-09 23:48:35 +00001333 continue;
1334 }
1335 }
1336 // fall through
1337
1338 case TemplateArgument::Type: {
1339 // We have a template template parameter but the template
1340 // argument does not refer to a template.
1341 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
1342 Invalid = true;
1343 break;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001344 }
1345
Douglas Gregor40808ce2009-03-09 23:48:35 +00001346 case TemplateArgument::Declaration:
1347 // We've already checked this template argument, so just copy
1348 // it to the list of converted arguments.
Anders Carlssonfb250522009-06-23 01:26:57 +00001349 Converted.Append(Arg);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001350 break;
1351
1352 case TemplateArgument::Integral:
1353 assert(false && "Integral argument with template template parameter");
1354 break;
Anders Carlssond01b1da2009-06-15 17:04:53 +00001355
1356 case TemplateArgument::Pack:
1357 assert(0 && "FIXME: Implement!");
1358 break;
Douglas Gregor40808ce2009-03-09 23:48:35 +00001359 }
Douglas Gregorc15cb382009-02-09 23:23:08 +00001360 }
1361 }
1362
1363 return Invalid;
1364}
1365
1366/// \brief Check a template argument against its corresponding
1367/// template type parameter.
1368///
1369/// This routine implements the semantics of C++ [temp.arg.type]. It
1370/// returns true if an error occurred, and false otherwise.
1371bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
1372 QualType Arg, SourceLocation ArgLoc) {
1373 // C++ [temp.arg.type]p2:
1374 // A local type, a type with no linkage, an unnamed type or a type
1375 // compounded from any of these types shall not be used as a
1376 // template-argument for a template type-parameter.
1377 //
1378 // FIXME: Perform the recursive and no-linkage type checks.
1379 const TagType *Tag = 0;
1380 if (const EnumType *EnumT = Arg->getAsEnumType())
1381 Tag = EnumT;
Ted Kremenek35366a62009-07-17 17:50:17 +00001382 else if (const RecordType *RecordT = Arg->getAsRecordType())
Douglas Gregorc15cb382009-02-09 23:23:08 +00001383 Tag = RecordT;
1384 if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod())
1385 return Diag(ArgLoc, diag::err_template_arg_local_type)
1386 << QualType(Tag, 0);
Douglas Gregor98137532009-03-10 18:33:27 +00001387 else if (Tag && !Tag->getDecl()->getDeclName() &&
1388 !Tag->getDecl()->getTypedefForAnonDecl()) {
Douglas Gregorc15cb382009-02-09 23:23:08 +00001389 Diag(ArgLoc, diag::err_template_arg_unnamed_type);
1390 Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here);
1391 return true;
1392 }
1393
1394 return false;
1395}
1396
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001397/// \brief Checks whether the given template argument is the address
1398/// of an object or function according to C++ [temp.arg.nontype]p1.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001399bool Sema::CheckTemplateArgumentAddressOfObjectOrFunction(Expr *Arg,
1400 NamedDecl *&Entity) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001401 bool Invalid = false;
1402
1403 // See through any implicit casts we added to fix the type.
1404 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
1405 Arg = Cast->getSubExpr();
1406
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001407 // C++0x allows nullptr, and there's no further checking to be done for that.
1408 if (Arg->getType()->isNullPtrType())
1409 return false;
1410
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001411 // C++ [temp.arg.nontype]p1:
1412 //
1413 // A template-argument for a non-type, non-template
1414 // template-parameter shall be one of: [...]
1415 //
1416 // -- the address of an object or function with external
1417 // linkage, including function templates and function
1418 // template-ids but excluding non-static class members,
1419 // expressed as & id-expression where the & is optional if
1420 // the name refers to a function or array, or if the
1421 // corresponding template-parameter is a reference; or
1422 DeclRefExpr *DRE = 0;
1423
1424 // Ignore (and complain about) any excess parentheses.
1425 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
1426 if (!Invalid) {
1427 Diag(Arg->getSourceRange().getBegin(),
1428 diag::err_template_arg_extra_parens)
1429 << Arg->getSourceRange();
1430 Invalid = true;
1431 }
1432
1433 Arg = Parens->getSubExpr();
1434 }
1435
1436 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
1437 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
1438 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
1439 } else
1440 DRE = dyn_cast<DeclRefExpr>(Arg);
1441
1442 if (!DRE || !isa<ValueDecl>(DRE->getDecl()))
1443 return Diag(Arg->getSourceRange().getBegin(),
1444 diag::err_template_arg_not_object_or_func_form)
1445 << Arg->getSourceRange();
1446
1447 // Cannot refer to non-static data members
1448 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl()))
1449 return Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
1450 << Field << Arg->getSourceRange();
1451
1452 // Cannot refer to non-static member functions
1453 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
1454 if (!Method->isStatic())
1455 return Diag(Arg->getSourceRange().getBegin(),
1456 diag::err_template_arg_method)
1457 << Method << Arg->getSourceRange();
1458
1459 // Functions must have external linkage.
1460 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
1461 if (Func->getStorageClass() == FunctionDecl::Static) {
1462 Diag(Arg->getSourceRange().getBegin(),
1463 diag::err_template_arg_function_not_extern)
1464 << Func << Arg->getSourceRange();
1465 Diag(Func->getLocation(), diag::note_template_arg_internal_object)
1466 << true;
1467 return true;
1468 }
1469
1470 // Okay: we've named a function with external linkage.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001471 Entity = Func;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001472 return Invalid;
1473 }
1474
1475 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
1476 if (!Var->hasGlobalStorage()) {
1477 Diag(Arg->getSourceRange().getBegin(),
1478 diag::err_template_arg_object_not_extern)
1479 << Var << Arg->getSourceRange();
1480 Diag(Var->getLocation(), diag::note_template_arg_internal_object)
1481 << true;
1482 return true;
1483 }
1484
1485 // Okay: we've named an object with external linkage
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001486 Entity = Var;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001487 return Invalid;
1488 }
1489
1490 // We found something else, but we don't know specifically what it is.
1491 Diag(Arg->getSourceRange().getBegin(),
1492 diag::err_template_arg_not_object_or_func)
1493 << Arg->getSourceRange();
1494 Diag(DRE->getDecl()->getLocation(),
1495 diag::note_template_arg_refers_here);
1496 return true;
1497}
1498
1499/// \brief Checks whether the given template argument is a pointer to
1500/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001501bool
1502Sema::CheckTemplateArgumentPointerToMember(Expr *Arg, NamedDecl *&Member) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001503 bool Invalid = false;
1504
1505 // See through any implicit casts we added to fix the type.
1506 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
1507 Arg = Cast->getSubExpr();
1508
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001509 // C++0x allows nullptr, and there's no further checking to be done for that.
1510 if (Arg->getType()->isNullPtrType())
1511 return false;
1512
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001513 // C++ [temp.arg.nontype]p1:
1514 //
1515 // A template-argument for a non-type, non-template
1516 // template-parameter shall be one of: [...]
1517 //
1518 // -- a pointer to member expressed as described in 5.3.1.
1519 QualifiedDeclRefExpr *DRE = 0;
1520
1521 // Ignore (and complain about) any excess parentheses.
1522 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
1523 if (!Invalid) {
1524 Diag(Arg->getSourceRange().getBegin(),
1525 diag::err_template_arg_extra_parens)
1526 << Arg->getSourceRange();
1527 Invalid = true;
1528 }
1529
1530 Arg = Parens->getSubExpr();
1531 }
1532
1533 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg))
1534 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
1535 DRE = dyn_cast<QualifiedDeclRefExpr>(UnOp->getSubExpr());
1536
1537 if (!DRE)
1538 return Diag(Arg->getSourceRange().getBegin(),
1539 diag::err_template_arg_not_pointer_to_member_form)
1540 << Arg->getSourceRange();
1541
1542 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
1543 assert((isa<FieldDecl>(DRE->getDecl()) ||
1544 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
1545 "Only non-static member pointers can make it here");
1546
1547 // Okay: this is the address of a non-static member, and therefore
1548 // a member pointer constant.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001549 Member = DRE->getDecl();
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001550 return Invalid;
1551 }
1552
1553 // We found something else, but we don't know specifically what it is.
1554 Diag(Arg->getSourceRange().getBegin(),
1555 diag::err_template_arg_not_pointer_to_member_form)
1556 << Arg->getSourceRange();
1557 Diag(DRE->getDecl()->getLocation(),
1558 diag::note_template_arg_refers_here);
1559 return true;
1560}
1561
Douglas Gregorc15cb382009-02-09 23:23:08 +00001562/// \brief Check a template argument against its corresponding
1563/// non-type template parameter.
1564///
Douglas Gregor2943aed2009-03-03 04:44:36 +00001565/// This routine implements the semantics of C++ [temp.arg.nontype].
1566/// It returns true if an error occurred, and false otherwise. \p
1567/// InstantiatedParamType is the type of the non-type template
1568/// parameter after it has been instantiated.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001569///
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001570/// If no error was detected, Converted receives the converted template argument.
Douglas Gregorc15cb382009-02-09 23:23:08 +00001571bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Douglas Gregor2943aed2009-03-03 04:44:36 +00001572 QualType InstantiatedParamType, Expr *&Arg,
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001573 TemplateArgument &Converted) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00001574 SourceLocation StartLoc = Arg->getSourceRange().getBegin();
1575
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001576 // If either the parameter has a dependent type or the argument is
1577 // type-dependent, there's nothing we can check now.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001578 // FIXME: Add template argument to Converted!
Douglas Gregor40808ce2009-03-09 23:48:35 +00001579 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
1580 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001581 Converted = TemplateArgument(Arg);
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001582 return false;
Douglas Gregor40808ce2009-03-09 23:48:35 +00001583 }
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001584
1585 // C++ [temp.arg.nontype]p5:
1586 // The following conversions are performed on each expression used
1587 // as a non-type template-argument. If a non-type
1588 // template-argument cannot be converted to the type of the
1589 // corresponding template-parameter then the program is
1590 // ill-formed.
1591 //
1592 // -- for a non-type template-parameter of integral or
1593 // enumeration type, integral promotions (4.5) and integral
1594 // conversions (4.7) are applied.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001595 QualType ParamType = InstantiatedParamType;
Douglas Gregora35284b2009-02-11 00:19:33 +00001596 QualType ArgType = Arg->getType();
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001597 if (ParamType->isIntegralType() || ParamType->isEnumeralType()) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001598 // C++ [temp.arg.nontype]p1:
1599 // A template-argument for a non-type, non-template
1600 // template-parameter shall be one of:
1601 //
1602 // -- an integral constant-expression of integral or enumeration
1603 // type; or
1604 // -- the name of a non-type template-parameter; or
1605 SourceLocation NonConstantLoc;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001606 llvm::APSInt Value;
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001607 if (!ArgType->isIntegralType() && !ArgType->isEnumeralType()) {
1608 Diag(Arg->getSourceRange().getBegin(),
1609 diag::err_template_arg_not_integral_or_enumeral)
1610 << ArgType << Arg->getSourceRange();
1611 Diag(Param->getLocation(), diag::note_template_param_here);
1612 return true;
1613 } else if (!Arg->isValueDependent() &&
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001614 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001615 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
1616 << ArgType << Arg->getSourceRange();
1617 return true;
1618 }
1619
1620 // FIXME: We need some way to more easily get the unqualified form
1621 // of the types without going all the way to the
1622 // canonical type.
1623 if (Context.getCanonicalType(ParamType).getCVRQualifiers())
1624 ParamType = Context.getCanonicalType(ParamType).getUnqualifiedType();
1625 if (Context.getCanonicalType(ArgType).getCVRQualifiers())
1626 ArgType = Context.getCanonicalType(ArgType).getUnqualifiedType();
1627
1628 // Try to convert the argument to the parameter's type.
1629 if (ParamType == ArgType) {
1630 // Okay: no conversion necessary
1631 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
1632 !ParamType->isEnumeralType()) {
1633 // This is an integral promotion or conversion.
1634 ImpCastExprToType(Arg, ParamType);
1635 } else {
1636 // We can't perform this conversion.
1637 Diag(Arg->getSourceRange().getBegin(),
1638 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00001639 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001640 Diag(Param->getLocation(), diag::note_template_param_here);
1641 return true;
1642 }
1643
Douglas Gregorf80a9d52009-03-14 00:20:21 +00001644 QualType IntegerType = Context.getCanonicalType(ParamType);
1645 if (const EnumType *Enum = IntegerType->getAsEnumType())
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001646 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregorf80a9d52009-03-14 00:20:21 +00001647
1648 if (!Arg->isValueDependent()) {
1649 // Check that an unsigned parameter does not receive a negative
1650 // value.
1651 if (IntegerType->isUnsignedIntegerType()
1652 && (Value.isSigned() && Value.isNegative())) {
1653 Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_negative)
1654 << Value.toString(10) << Param->getType()
1655 << Arg->getSourceRange();
1656 Diag(Param->getLocation(), diag::note_template_param_here);
1657 return true;
1658 }
1659
1660 // Check that we don't overflow the template parameter type.
1661 unsigned AllowedBits = Context.getTypeSize(IntegerType);
1662 if (Value.getActiveBits() > AllowedBits) {
1663 Diag(Arg->getSourceRange().getBegin(),
1664 diag::err_template_arg_too_large)
1665 << Value.toString(10) << Param->getType()
1666 << Arg->getSourceRange();
1667 Diag(Param->getLocation(), diag::note_template_param_here);
1668 return true;
1669 }
1670
1671 if (Value.getBitWidth() != AllowedBits)
1672 Value.extOrTrunc(AllowedBits);
1673 Value.setIsSigned(IntegerType->isSignedIntegerType());
1674 }
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001675
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001676 // Add the value of this argument to the list of converted
1677 // arguments. We use the bitwidth and signedness of the template
1678 // parameter.
1679 if (Arg->isValueDependent()) {
1680 // The argument is value-dependent. Create a new
1681 // TemplateArgument with the converted expression.
1682 Converted = TemplateArgument(Arg);
1683 return false;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001684 }
1685
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001686 Converted = TemplateArgument(StartLoc, Value,
1687 ParamType->isEnumeralType() ? ParamType
1688 : IntegerType);
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001689 return false;
1690 }
Douglas Gregora35284b2009-02-11 00:19:33 +00001691
Douglas Gregorb86b0572009-02-11 01:18:59 +00001692 // Handle pointer-to-function, reference-to-function, and
1693 // pointer-to-member-function all in (roughly) the same way.
1694 if (// -- For a non-type template-parameter of type pointer to
1695 // function, only the function-to-pointer conversion (4.3) is
1696 // applied. If the template-argument represents a set of
1697 // overloaded functions (or a pointer to such), the matching
1698 // function is selected from the set (13.4).
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001699 // In C++0x, any std::nullptr_t value can be converted.
Douglas Gregorb86b0572009-02-11 01:18:59 +00001700 (ParamType->isPointerType() &&
Ted Kremenek35366a62009-07-17 17:50:17 +00001701 ParamType->getAsPointerType()->getPointeeType()->isFunctionType()) ||
Douglas Gregorb86b0572009-02-11 01:18:59 +00001702 // -- For a non-type template-parameter of type reference to
1703 // function, no conversions apply. If the template-argument
1704 // represents a set of overloaded functions, the matching
1705 // function is selected from the set (13.4).
1706 (ParamType->isReferenceType() &&
Ted Kremenek35366a62009-07-17 17:50:17 +00001707 ParamType->getAsReferenceType()->getPointeeType()->isFunctionType()) ||
Douglas Gregorb86b0572009-02-11 01:18:59 +00001708 // -- For a non-type template-parameter of type pointer to
1709 // member function, no conversions apply. If the
1710 // template-argument represents a set of overloaded member
1711 // functions, the matching member function is selected from
1712 // the set (13.4).
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001713 // Again, C++0x allows a std::nullptr_t value.
Douglas Gregorb86b0572009-02-11 01:18:59 +00001714 (ParamType->isMemberPointerType() &&
Ted Kremenek35366a62009-07-17 17:50:17 +00001715 ParamType->getAsMemberPointerType()->getPointeeType()
Douglas Gregorb86b0572009-02-11 01:18:59 +00001716 ->isFunctionType())) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001717 if (Context.hasSameUnqualifiedType(ArgType,
1718 ParamType.getNonReferenceType())) {
Douglas Gregora35284b2009-02-11 00:19:33 +00001719 // We don't have to do anything: the types already match.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001720 } else if (ArgType->isNullPtrType() && (ParamType->isPointerType() ||
1721 ParamType->isMemberPointerType())) {
1722 ArgType = ParamType;
1723 ImpCastExprToType(Arg, ParamType);
Douglas Gregorb86b0572009-02-11 01:18:59 +00001724 } else if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregora35284b2009-02-11 00:19:33 +00001725 ArgType = Context.getPointerType(ArgType);
1726 ImpCastExprToType(Arg, ArgType);
1727 } else if (FunctionDecl *Fn
1728 = ResolveAddressOfOverloadedFunction(Arg, ParamType, true)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001729 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
1730 return true;
1731
Douglas Gregora35284b2009-02-11 00:19:33 +00001732 FixOverloadedFunctionReference(Arg, Fn);
1733 ArgType = Arg->getType();
Douglas Gregorb86b0572009-02-11 01:18:59 +00001734 if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregora35284b2009-02-11 00:19:33 +00001735 ArgType = Context.getPointerType(Arg->getType());
1736 ImpCastExprToType(Arg, ArgType);
1737 }
1738 }
1739
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001740 if (!Context.hasSameUnqualifiedType(ArgType,
1741 ParamType.getNonReferenceType())) {
Douglas Gregora35284b2009-02-11 00:19:33 +00001742 // We can't perform this conversion.
1743 Diag(Arg->getSourceRange().getBegin(),
1744 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00001745 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregora35284b2009-02-11 00:19:33 +00001746 Diag(Param->getLocation(), diag::note_template_param_here);
1747 return true;
1748 }
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001749
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001750 if (ParamType->isMemberPointerType()) {
1751 NamedDecl *Member = 0;
1752 if (CheckTemplateArgumentPointerToMember(Arg, Member))
1753 return true;
1754
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00001755 if (Member)
1756 Member = cast<NamedDecl>(Member->getCanonicalDecl());
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001757 Converted = TemplateArgument(StartLoc, Member);
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001758 return false;
1759 }
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001760
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001761 NamedDecl *Entity = 0;
1762 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1763 return true;
1764
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00001765 if (Entity)
1766 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001767 Converted = TemplateArgument(StartLoc, Entity);
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001768 return false;
Douglas Gregora35284b2009-02-11 00:19:33 +00001769 }
1770
Chris Lattnerfe90de72009-02-20 21:37:53 +00001771 if (ParamType->isPointerType()) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00001772 // -- for a non-type template-parameter of type pointer to
1773 // object, qualification conversions (4.4) and the
1774 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001775 // C++0x also allows a value of std::nullptr_t.
Ted Kremenek35366a62009-07-17 17:50:17 +00001776 assert(ParamType->getAsPointerType()->getPointeeType()->isObjectType() &&
Douglas Gregorb86b0572009-02-11 01:18:59 +00001777 "Only object pointers allowed here");
Douglas Gregorf684e6e2009-02-11 00:44:29 +00001778
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001779 if (ArgType->isNullPtrType()) {
1780 ArgType = ParamType;
1781 ImpCastExprToType(Arg, ParamType);
1782 } else if (ArgType->isArrayType()) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00001783 ArgType = Context.getArrayDecayedType(ArgType);
1784 ImpCastExprToType(Arg, ArgType);
Douglas Gregorf684e6e2009-02-11 00:44:29 +00001785 }
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001786
Douglas Gregorb86b0572009-02-11 01:18:59 +00001787 if (IsQualificationConversion(ArgType, ParamType)) {
1788 ArgType = ParamType;
1789 ImpCastExprToType(Arg, ParamType);
1790 }
1791
Douglas Gregor8e6563b2009-02-11 18:22:40 +00001792 if (!Context.hasSameUnqualifiedType(ArgType, ParamType)) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00001793 // We can't perform this conversion.
1794 Diag(Arg->getSourceRange().getBegin(),
1795 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00001796 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregorb86b0572009-02-11 01:18:59 +00001797 Diag(Param->getLocation(), diag::note_template_param_here);
1798 return true;
1799 }
1800
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001801 NamedDecl *Entity = 0;
1802 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1803 return true;
1804
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00001805 if (Entity)
1806 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001807 Converted = TemplateArgument(StartLoc, Entity);
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001808 return false;
Douglas Gregorf684e6e2009-02-11 00:44:29 +00001809 }
Douglas Gregorb86b0572009-02-11 01:18:59 +00001810
Ted Kremenek35366a62009-07-17 17:50:17 +00001811 if (const ReferenceType *ParamRefType = ParamType->getAsReferenceType()) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00001812 // -- For a non-type template-parameter of type reference to
1813 // object, no conversions apply. The type referred to by the
1814 // reference may be more cv-qualified than the (otherwise
1815 // identical) type of the template-argument. The
1816 // template-parameter is bound directly to the
1817 // template-argument, which must be an lvalue.
Douglas Gregorbad0e652009-03-24 20:32:41 +00001818 assert(ParamRefType->getPointeeType()->isObjectType() &&
Douglas Gregorb86b0572009-02-11 01:18:59 +00001819 "Only object references allowed here");
Douglas Gregorf684e6e2009-02-11 00:44:29 +00001820
Douglas Gregor8e6563b2009-02-11 18:22:40 +00001821 if (!Context.hasSameUnqualifiedType(ParamRefType->getPointeeType(), ArgType)) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00001822 Diag(Arg->getSourceRange().getBegin(),
1823 diag::err_template_arg_no_ref_bind)
Douglas Gregor2943aed2009-03-03 04:44:36 +00001824 << InstantiatedParamType << Arg->getType()
Douglas Gregorb86b0572009-02-11 01:18:59 +00001825 << Arg->getSourceRange();
1826 Diag(Param->getLocation(), diag::note_template_param_here);
1827 return true;
1828 }
1829
1830 unsigned ParamQuals
1831 = Context.getCanonicalType(ParamType).getCVRQualifiers();
1832 unsigned ArgQuals = Context.getCanonicalType(ArgType).getCVRQualifiers();
1833
1834 if ((ParamQuals | ArgQuals) != ParamQuals) {
1835 Diag(Arg->getSourceRange().getBegin(),
1836 diag::err_template_arg_ref_bind_ignores_quals)
Douglas Gregor2943aed2009-03-03 04:44:36 +00001837 << InstantiatedParamType << Arg->getType()
Douglas Gregorb86b0572009-02-11 01:18:59 +00001838 << Arg->getSourceRange();
1839 Diag(Param->getLocation(), diag::note_template_param_here);
1840 return true;
1841 }
1842
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001843 NamedDecl *Entity = 0;
1844 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1845 return true;
1846
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00001847 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001848 Converted = TemplateArgument(StartLoc, Entity);
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001849 return false;
Douglas Gregorb86b0572009-02-11 01:18:59 +00001850 }
Douglas Gregor658bbb52009-02-11 16:16:59 +00001851
1852 // -- For a non-type template-parameter of type pointer to data
1853 // member, qualification conversions (4.4) are applied.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001854 // C++0x allows std::nullptr_t values.
Douglas Gregor658bbb52009-02-11 16:16:59 +00001855 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
1856
Douglas Gregor8e6563b2009-02-11 18:22:40 +00001857 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
Douglas Gregor658bbb52009-02-11 16:16:59 +00001858 // Types match exactly: nothing more to do here.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001859 } else if (ArgType->isNullPtrType()) {
1860 ImpCastExprToType(Arg, ParamType);
Douglas Gregor658bbb52009-02-11 16:16:59 +00001861 } else if (IsQualificationConversion(ArgType, ParamType)) {
1862 ImpCastExprToType(Arg, ParamType);
1863 } else {
1864 // We can't perform this conversion.
1865 Diag(Arg->getSourceRange().getBegin(),
1866 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00001867 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor658bbb52009-02-11 16:16:59 +00001868 Diag(Param->getLocation(), diag::note_template_param_here);
1869 return true;
1870 }
1871
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001872 NamedDecl *Member = 0;
1873 if (CheckTemplateArgumentPointerToMember(Arg, Member))
1874 return true;
1875
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00001876 if (Member)
1877 Member = cast<NamedDecl>(Member->getCanonicalDecl());
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001878 Converted = TemplateArgument(StartLoc, Member);
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001879 return false;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001880}
1881
1882/// \brief Check a template argument against its corresponding
1883/// template template parameter.
1884///
1885/// This routine implements the semantics of C++ [temp.arg.template].
1886/// It returns true if an error occurred, and false otherwise.
1887bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
1888 DeclRefExpr *Arg) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00001889 assert(isa<TemplateDecl>(Arg->getDecl()) && "Only template decls allowed");
1890 TemplateDecl *Template = cast<TemplateDecl>(Arg->getDecl());
1891
1892 // C++ [temp.arg.template]p1:
1893 // A template-argument for a template template-parameter shall be
1894 // the name of a class template, expressed as id-expression. Only
1895 // primary class templates are considered when matching the
1896 // template template argument with the corresponding parameter;
1897 // partial specializations are not considered even if their
1898 // parameter lists match that of the template template parameter.
Douglas Gregorba1ecb52009-06-12 19:43:02 +00001899 //
1900 // Note that we also allow template template parameters here, which
1901 // will happen when we are dealing with, e.g., class template
1902 // partial specializations.
1903 if (!isa<ClassTemplateDecl>(Template) &&
1904 !isa<TemplateTemplateParmDecl>(Template)) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00001905 assert(isa<FunctionTemplateDecl>(Template) &&
1906 "Only function templates are possible here");
Douglas Gregore53060f2009-06-25 22:08:12 +00001907 Diag(Arg->getLocStart(), diag::err_template_arg_not_class_template);
1908 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
Douglas Gregordd0574e2009-02-10 00:24:35 +00001909 << Template;
1910 }
1911
1912 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
1913 Param->getTemplateParameters(),
1914 true, true,
1915 Arg->getSourceRange().getBegin());
Douglas Gregorc15cb382009-02-09 23:23:08 +00001916}
1917
Douglas Gregorddc29e12009-02-06 22:42:48 +00001918/// \brief Determine whether the given template parameter lists are
1919/// equivalent.
1920///
1921/// \param New The new template parameter list, typically written in the
1922/// source code as part of a new template declaration.
1923///
1924/// \param Old The old template parameter list, typically found via
1925/// name lookup of the template declared with this template parameter
1926/// list.
1927///
1928/// \param Complain If true, this routine will produce a diagnostic if
1929/// the template parameter lists are not equivalent.
1930///
Douglas Gregordd0574e2009-02-10 00:24:35 +00001931/// \param IsTemplateTemplateParm If true, this routine is being
1932/// called to compare the template parameter lists of a template
1933/// template parameter.
1934///
1935/// \param TemplateArgLoc If this source location is valid, then we
1936/// are actually checking the template parameter list of a template
1937/// argument (New) against the template parameter list of its
1938/// corresponding template template parameter (Old). We produce
1939/// slightly different diagnostics in this scenario.
1940///
Douglas Gregorddc29e12009-02-06 22:42:48 +00001941/// \returns True if the template parameter lists are equal, false
1942/// otherwise.
1943bool
1944Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
1945 TemplateParameterList *Old,
1946 bool Complain,
Douglas Gregordd0574e2009-02-10 00:24:35 +00001947 bool IsTemplateTemplateParm,
1948 SourceLocation TemplateArgLoc) {
Douglas Gregorddc29e12009-02-06 22:42:48 +00001949 if (Old->size() != New->size()) {
1950 if (Complain) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00001951 unsigned NextDiag = diag::err_template_param_list_different_arity;
1952 if (TemplateArgLoc.isValid()) {
1953 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
1954 NextDiag = diag::note_template_param_list_different_arity;
1955 }
1956 Diag(New->getTemplateLoc(), NextDiag)
1957 << (New->size() > Old->size())
1958 << IsTemplateTemplateParm
1959 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
Douglas Gregorddc29e12009-02-06 22:42:48 +00001960 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
1961 << IsTemplateTemplateParm
1962 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
1963 }
1964
1965 return false;
1966 }
1967
1968 for (TemplateParameterList::iterator OldParm = Old->begin(),
1969 OldParmEnd = Old->end(), NewParm = New->begin();
1970 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
1971 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
Douglas Gregor34d1dc92009-06-24 16:50:40 +00001972 if (Complain) {
1973 unsigned NextDiag = diag::err_template_param_different_kind;
1974 if (TemplateArgLoc.isValid()) {
1975 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
1976 NextDiag = diag::note_template_param_different_kind;
1977 }
1978 Diag((*NewParm)->getLocation(), NextDiag)
1979 << IsTemplateTemplateParm;
1980 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
1981 << IsTemplateTemplateParm;
Douglas Gregordd0574e2009-02-10 00:24:35 +00001982 }
Douglas Gregorddc29e12009-02-06 22:42:48 +00001983 return false;
1984 }
1985
1986 if (isa<TemplateTypeParmDecl>(*OldParm)) {
1987 // Okay; all template type parameters are equivalent (since we
Douglas Gregordd0574e2009-02-10 00:24:35 +00001988 // know we're at the same index).
1989#if 0
Mike Stump390b4cc2009-05-16 07:39:55 +00001990 // FIXME: Enable this code in debug mode *after* we properly go through
1991 // and "instantiate" the template parameter lists of template template
1992 // parameters. It's only after this instantiation that (1) any dependent
1993 // types within the template parameter list of the template template
1994 // parameter can be checked, and (2) the template type parameter depths
Douglas Gregordd0574e2009-02-10 00:24:35 +00001995 // will match up.
Douglas Gregorddc29e12009-02-06 22:42:48 +00001996 QualType OldParmType
1997 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*OldParm));
1998 QualType NewParmType
1999 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*NewParm));
2000 assert(Context.getCanonicalType(OldParmType) ==
2001 Context.getCanonicalType(NewParmType) &&
2002 "type parameter mismatch?");
2003#endif
2004 } else if (NonTypeTemplateParmDecl *OldNTTP
2005 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
2006 // The types of non-type template parameters must agree.
2007 NonTypeTemplateParmDecl *NewNTTP
2008 = cast<NonTypeTemplateParmDecl>(*NewParm);
2009 if (Context.getCanonicalType(OldNTTP->getType()) !=
2010 Context.getCanonicalType(NewNTTP->getType())) {
2011 if (Complain) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00002012 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
2013 if (TemplateArgLoc.isValid()) {
2014 Diag(TemplateArgLoc,
2015 diag::err_template_arg_template_params_mismatch);
2016 NextDiag = diag::note_template_nontype_parm_different_type;
2017 }
2018 Diag(NewNTTP->getLocation(), NextDiag)
Douglas Gregorddc29e12009-02-06 22:42:48 +00002019 << NewNTTP->getType()
2020 << IsTemplateTemplateParm;
2021 Diag(OldNTTP->getLocation(),
2022 diag::note_template_nontype_parm_prev_declaration)
2023 << OldNTTP->getType();
2024 }
2025 return false;
2026 }
2027 } else {
2028 // The template parameter lists of template template
2029 // parameters must agree.
2030 // FIXME: Could we perform a faster "type" comparison here?
2031 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
2032 "Only template template parameters handled here");
2033 TemplateTemplateParmDecl *OldTTP
2034 = cast<TemplateTemplateParmDecl>(*OldParm);
2035 TemplateTemplateParmDecl *NewTTP
2036 = cast<TemplateTemplateParmDecl>(*NewParm);
2037 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
2038 OldTTP->getTemplateParameters(),
2039 Complain,
Douglas Gregordd0574e2009-02-10 00:24:35 +00002040 /*IsTemplateTemplateParm=*/true,
2041 TemplateArgLoc))
Douglas Gregorddc29e12009-02-06 22:42:48 +00002042 return false;
2043 }
2044 }
2045
2046 return true;
2047}
2048
2049/// \brief Check whether a template can be declared within this scope.
2050///
2051/// If the template declaration is valid in this scope, returns
2052/// false. Otherwise, issues a diagnostic and returns true.
2053bool
2054Sema::CheckTemplateDeclScope(Scope *S,
2055 MultiTemplateParamsArg &TemplateParameterLists) {
2056 assert(TemplateParameterLists.size() > 0 && "Not a template");
2057
2058 // Find the nearest enclosing declaration scope.
2059 while ((S->getFlags() & Scope::DeclScope) == 0 ||
2060 (S->getFlags() & Scope::TemplateParamScope) != 0)
2061 S = S->getParent();
2062
2063 TemplateParameterList *TemplateParams =
2064 static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
2065 SourceLocation TemplateLoc = TemplateParams->getTemplateLoc();
2066 SourceRange TemplateRange
2067 = SourceRange(TemplateLoc, TemplateParams->getRAngleLoc());
2068
2069 // C++ [temp]p2:
2070 // A template-declaration can appear only as a namespace scope or
2071 // class scope declaration.
2072 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
2073 while (Ctx && isa<LinkageSpecDecl>(Ctx)) {
2074 if (cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
2075 return Diag(TemplateLoc, diag::err_template_linkage)
2076 << TemplateRange;
2077
2078 Ctx = Ctx->getParent();
2079 }
2080
2081 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
2082 return false;
2083
2084 return Diag(TemplateLoc, diag::err_template_outside_namespace_or_class_scope)
2085 << TemplateRange;
2086}
Douglas Gregorcc636682009-02-17 23:15:12 +00002087
Douglas Gregorff668032009-05-13 18:28:20 +00002088/// \brief Check whether a class template specialization or explicit
2089/// instantiation in the current context is well-formed.
Douglas Gregor88b70942009-02-25 22:02:03 +00002090///
Douglas Gregorff668032009-05-13 18:28:20 +00002091/// This routine determines whether a class template specialization or
2092/// explicit instantiation can be declared in the current context
2093/// (C++ [temp.expl.spec]p2, C++0x [temp.explicit]p2) and emits
2094/// appropriate diagnostics if there was an error. It returns true if
2095// there was an error that we cannot recover from, and false otherwise.
Douglas Gregor88b70942009-02-25 22:02:03 +00002096bool
2097Sema::CheckClassTemplateSpecializationScope(ClassTemplateDecl *ClassTemplate,
2098 ClassTemplateSpecializationDecl *PrevDecl,
2099 SourceLocation TemplateNameLoc,
Douglas Gregorff668032009-05-13 18:28:20 +00002100 SourceRange ScopeSpecifierRange,
Douglas Gregor16df8502009-06-12 22:21:45 +00002101 bool PartialSpecialization,
Douglas Gregorff668032009-05-13 18:28:20 +00002102 bool ExplicitInstantiation) {
Douglas Gregor88b70942009-02-25 22:02:03 +00002103 // C++ [temp.expl.spec]p2:
2104 // An explicit specialization shall be declared in the namespace
2105 // of which the template is a member, or, for member templates, in
2106 // the namespace of which the enclosing class or enclosing class
2107 // template is a member. An explicit specialization of a member
2108 // function, member class or static data member of a class
2109 // template shall be declared in the namespace of which the class
2110 // template is a member. Such a declaration may also be a
2111 // definition. If the declaration is not a definition, the
2112 // specialization may be defined later in the name- space in which
2113 // the explicit specialization was declared, or in a namespace
2114 // that encloses the one in which the explicit specialization was
2115 // declared.
2116 if (CurContext->getLookupContext()->isFunctionOrMethod()) {
Douglas Gregor16df8502009-06-12 22:21:45 +00002117 int Kind = ExplicitInstantiation? 2 : PartialSpecialization? 1 : 0;
Douglas Gregor88b70942009-02-25 22:02:03 +00002118 Diag(TemplateNameLoc, diag::err_template_spec_decl_function_scope)
Douglas Gregor16df8502009-06-12 22:21:45 +00002119 << Kind << ClassTemplate;
Douglas Gregor88b70942009-02-25 22:02:03 +00002120 return true;
2121 }
2122
2123 DeclContext *DC = CurContext->getEnclosingNamespaceContext();
2124 DeclContext *TemplateContext
2125 = ClassTemplate->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregorff668032009-05-13 18:28:20 +00002126 if ((!PrevDecl || PrevDecl->getSpecializationKind() == TSK_Undeclared) &&
2127 !ExplicitInstantiation) {
Douglas Gregor88b70942009-02-25 22:02:03 +00002128 // There is no prior declaration of this entity, so this
2129 // specialization must be in the same context as the template
2130 // itself.
2131 if (DC != TemplateContext) {
2132 if (isa<TranslationUnitDecl>(TemplateContext))
2133 Diag(TemplateNameLoc, diag::err_template_spec_decl_out_of_scope_global)
Douglas Gregor16df8502009-06-12 22:21:45 +00002134 << PartialSpecialization
Douglas Gregor88b70942009-02-25 22:02:03 +00002135 << ClassTemplate << ScopeSpecifierRange;
2136 else if (isa<NamespaceDecl>(TemplateContext))
2137 Diag(TemplateNameLoc, diag::err_template_spec_decl_out_of_scope)
Douglas Gregor16df8502009-06-12 22:21:45 +00002138 << PartialSpecialization << ClassTemplate
2139 << cast<NamedDecl>(TemplateContext) << ScopeSpecifierRange;
Douglas Gregor88b70942009-02-25 22:02:03 +00002140
2141 Diag(ClassTemplate->getLocation(), diag::note_template_decl_here);
2142 }
2143
2144 return false;
2145 }
2146
2147 // We have a previous declaration of this entity. Make sure that
2148 // this redeclaration (or definition) occurs in an enclosing namespace.
2149 if (!CurContext->Encloses(TemplateContext)) {
Mike Stump390b4cc2009-05-16 07:39:55 +00002150 // FIXME: In C++98, we would like to turn these errors into warnings,
2151 // dependent on a -Wc++0x flag.
Douglas Gregorff668032009-05-13 18:28:20 +00002152 bool SuppressedDiag = false;
Douglas Gregor16df8502009-06-12 22:21:45 +00002153 int Kind = ExplicitInstantiation? 2 : PartialSpecialization? 1 : 0;
Douglas Gregorff668032009-05-13 18:28:20 +00002154 if (isa<TranslationUnitDecl>(TemplateContext)) {
2155 if (!ExplicitInstantiation || getLangOptions().CPlusPlus0x)
2156 Diag(TemplateNameLoc, diag::err_template_spec_redecl_global_scope)
Douglas Gregor16df8502009-06-12 22:21:45 +00002157 << Kind << ClassTemplate << ScopeSpecifierRange;
Douglas Gregorff668032009-05-13 18:28:20 +00002158 else
2159 SuppressedDiag = true;
2160 } else if (isa<NamespaceDecl>(TemplateContext)) {
2161 if (!ExplicitInstantiation || getLangOptions().CPlusPlus0x)
2162 Diag(TemplateNameLoc, diag::err_template_spec_redecl_out_of_scope)
Douglas Gregor16df8502009-06-12 22:21:45 +00002163 << Kind << ClassTemplate
Douglas Gregorff668032009-05-13 18:28:20 +00002164 << cast<NamedDecl>(TemplateContext) << ScopeSpecifierRange;
2165 else
2166 SuppressedDiag = true;
2167 }
Douglas Gregor88b70942009-02-25 22:02:03 +00002168
Douglas Gregorff668032009-05-13 18:28:20 +00002169 if (!SuppressedDiag)
2170 Diag(ClassTemplate->getLocation(), diag::note_template_decl_here);
Douglas Gregor88b70942009-02-25 22:02:03 +00002171 }
2172
2173 return false;
2174}
2175
Douglas Gregore94866f2009-06-12 21:21:02 +00002176/// \brief Check the non-type template arguments of a class template
2177/// partial specialization according to C++ [temp.class.spec]p9.
2178///
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002179/// \param TemplateParams the template parameters of the primary class
2180/// template.
2181///
2182/// \param TemplateArg the template arguments of the class template
2183/// partial specialization.
2184///
2185/// \param MirrorsPrimaryTemplate will be set true if the class
2186/// template partial specialization arguments are identical to the
2187/// implicit template arguments of the primary template. This is not
2188/// necessarily an error (C++0x), and it is left to the caller to diagnose
2189/// this condition when it is an error.
2190///
Douglas Gregore94866f2009-06-12 21:21:02 +00002191/// \returns true if there was an error, false otherwise.
2192bool Sema::CheckClassTemplatePartialSpecializationArgs(
2193 TemplateParameterList *TemplateParams,
Anders Carlsson6360be72009-06-13 18:20:51 +00002194 const TemplateArgumentListBuilder &TemplateArgs,
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002195 bool &MirrorsPrimaryTemplate) {
Douglas Gregore94866f2009-06-12 21:21:02 +00002196 // FIXME: the interface to this function will have to change to
2197 // accommodate variadic templates.
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002198 MirrorsPrimaryTemplate = true;
Anders Carlsson6360be72009-06-13 18:20:51 +00002199
Anders Carlssonfb250522009-06-23 01:26:57 +00002200 const TemplateArgument *ArgList = TemplateArgs.getFlatArguments();
Anders Carlsson6360be72009-06-13 18:20:51 +00002201
Douglas Gregore94866f2009-06-12 21:21:02 +00002202 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002203 // Determine whether the template argument list of the partial
2204 // specialization is identical to the implicit argument list of
2205 // the primary template. The caller may need to diagnostic this as
2206 // an error per C++ [temp.class.spec]p9b3.
2207 if (MirrorsPrimaryTemplate) {
2208 if (TemplateTypeParmDecl *TTP
2209 = dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(I))) {
2210 if (Context.getCanonicalType(Context.getTypeDeclType(TTP)) !=
Anders Carlsson6360be72009-06-13 18:20:51 +00002211 Context.getCanonicalType(ArgList[I].getAsType()))
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002212 MirrorsPrimaryTemplate = false;
2213 } else if (TemplateTemplateParmDecl *TTP
2214 = dyn_cast<TemplateTemplateParmDecl>(
2215 TemplateParams->getParam(I))) {
2216 // FIXME: We should settle on either Declaration storage or
2217 // Expression storage for template template parameters.
2218 TemplateTemplateParmDecl *ArgDecl
2219 = dyn_cast_or_null<TemplateTemplateParmDecl>(
Anders Carlsson6360be72009-06-13 18:20:51 +00002220 ArgList[I].getAsDecl());
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002221 if (!ArgDecl)
2222 if (DeclRefExpr *DRE
Anders Carlsson6360be72009-06-13 18:20:51 +00002223 = dyn_cast_or_null<DeclRefExpr>(ArgList[I].getAsExpr()))
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002224 ArgDecl = dyn_cast<TemplateTemplateParmDecl>(DRE->getDecl());
2225
2226 if (!ArgDecl ||
2227 ArgDecl->getIndex() != TTP->getIndex() ||
2228 ArgDecl->getDepth() != TTP->getDepth())
2229 MirrorsPrimaryTemplate = false;
2230 }
2231 }
2232
Douglas Gregore94866f2009-06-12 21:21:02 +00002233 NonTypeTemplateParmDecl *Param
2234 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002235 if (!Param) {
Douglas Gregore94866f2009-06-12 21:21:02 +00002236 continue;
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002237 }
2238
Anders Carlsson6360be72009-06-13 18:20:51 +00002239 Expr *ArgExpr = ArgList[I].getAsExpr();
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002240 if (!ArgExpr) {
2241 MirrorsPrimaryTemplate = false;
Douglas Gregore94866f2009-06-12 21:21:02 +00002242 continue;
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002243 }
Douglas Gregore94866f2009-06-12 21:21:02 +00002244
2245 // C++ [temp.class.spec]p8:
2246 // A non-type argument is non-specialized if it is the name of a
2247 // non-type parameter. All other non-type arguments are
2248 // specialized.
2249 //
2250 // Below, we check the two conditions that only apply to
2251 // specialized non-type arguments, so skip any non-specialized
2252 // arguments.
2253 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002254 if (NonTypeTemplateParmDecl *NTTP
2255 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl())) {
2256 if (MirrorsPrimaryTemplate &&
2257 (Param->getIndex() != NTTP->getIndex() ||
2258 Param->getDepth() != NTTP->getDepth()))
2259 MirrorsPrimaryTemplate = false;
2260
Douglas Gregore94866f2009-06-12 21:21:02 +00002261 continue;
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002262 }
Douglas Gregore94866f2009-06-12 21:21:02 +00002263
2264 // C++ [temp.class.spec]p9:
2265 // Within the argument list of a class template partial
2266 // specialization, the following restrictions apply:
2267 // -- A partially specialized non-type argument expression
2268 // shall not involve a template parameter of the partial
2269 // specialization except when the argument expression is a
2270 // simple identifier.
2271 if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
2272 Diag(ArgExpr->getLocStart(),
2273 diag::err_dependent_non_type_arg_in_partial_spec)
2274 << ArgExpr->getSourceRange();
2275 return true;
2276 }
2277
2278 // -- The type of a template parameter corresponding to a
2279 // specialized non-type argument shall not be dependent on a
2280 // parameter of the specialization.
2281 if (Param->getType()->isDependentType()) {
2282 Diag(ArgExpr->getLocStart(),
2283 diag::err_dependent_typed_non_type_arg_in_partial_spec)
2284 << Param->getType()
2285 << ArgExpr->getSourceRange();
2286 Diag(Param->getLocation(), diag::note_template_param_here);
2287 return true;
2288 }
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002289
2290 MirrorsPrimaryTemplate = false;
Douglas Gregore94866f2009-06-12 21:21:02 +00002291 }
2292
2293 return false;
2294}
2295
Douglas Gregor212e81c2009-03-25 00:13:59 +00002296Sema::DeclResult
Douglas Gregorcc636682009-02-17 23:15:12 +00002297Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec, TagKind TK,
2298 SourceLocation KWLoc,
2299 const CXXScopeSpec &SS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00002300 TemplateTy TemplateD,
Douglas Gregorcc636682009-02-17 23:15:12 +00002301 SourceLocation TemplateNameLoc,
2302 SourceLocation LAngleLoc,
Douglas Gregor40808ce2009-03-09 23:48:35 +00002303 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregorcc636682009-02-17 23:15:12 +00002304 SourceLocation *TemplateArgLocs,
2305 SourceLocation RAngleLoc,
2306 AttributeList *Attr,
2307 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregorcc636682009-02-17 23:15:12 +00002308 // Find the class template we're specializing
Douglas Gregor7532dc62009-03-30 22:58:21 +00002309 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Douglas Gregorcc636682009-02-17 23:15:12 +00002310 ClassTemplateDecl *ClassTemplate
Douglas Gregor7532dc62009-03-30 22:58:21 +00002311 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
Douglas Gregorcc636682009-02-17 23:15:12 +00002312
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002313 bool isPartialSpecialization = false;
2314
Douglas Gregor88b70942009-02-25 22:02:03 +00002315 // Check the validity of the template headers that introduce this
2316 // template.
Douglas Gregor6bc9f7e2009-02-25 22:18:32 +00002317 // FIXME: Once we have member templates, we'll need to check
2318 // C++ [temp.expl.spec]p17-18, where we could have multiple levels of
2319 // template<> headers.
Douglas Gregor4b2d3f72009-02-26 21:00:50 +00002320 if (TemplateParameterLists.size() == 0)
2321 Diag(KWLoc, diag::err_template_spec_needs_header)
Douglas Gregorb2fb6de2009-02-27 17:53:17 +00002322 << CodeModificationHint::CreateInsertion(KWLoc, "template<> ");
Douglas Gregor4b2d3f72009-02-26 21:00:50 +00002323 else {
Douglas Gregor88b70942009-02-25 22:02:03 +00002324 TemplateParameterList *TemplateParams
2325 = static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
Chris Lattnerb28317a2009-03-28 19:18:32 +00002326 if (TemplateParameterLists.size() > 1) {
2327 Diag(TemplateParams->getTemplateLoc(),
2328 diag::err_template_spec_extra_headers);
2329 return true;
2330 }
Douglas Gregor88b70942009-02-25 22:02:03 +00002331
Douglas Gregorba1ecb52009-06-12 19:43:02 +00002332 if (TemplateParams->size() > 0) {
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002333 isPartialSpecialization = true;
Douglas Gregorba1ecb52009-06-12 19:43:02 +00002334
2335 // C++ [temp.class.spec]p10:
2336 // The template parameter list of a specialization shall not
2337 // contain default template argument values.
2338 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
2339 Decl *Param = TemplateParams->getParam(I);
2340 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
2341 if (TTP->hasDefaultArgument()) {
2342 Diag(TTP->getDefaultArgumentLoc(),
2343 diag::err_default_arg_in_partial_spec);
2344 TTP->setDefaultArgument(QualType(), SourceLocation(), false);
2345 }
2346 } else if (NonTypeTemplateParmDecl *NTTP
2347 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2348 if (Expr *DefArg = NTTP->getDefaultArgument()) {
2349 Diag(NTTP->getDefaultArgumentLoc(),
2350 diag::err_default_arg_in_partial_spec)
2351 << DefArg->getSourceRange();
2352 NTTP->setDefaultArgument(0);
2353 DefArg->Destroy(Context);
2354 }
2355 } else {
2356 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
2357 if (Expr *DefArg = TTP->getDefaultArgument()) {
2358 Diag(TTP->getDefaultArgumentLoc(),
2359 diag::err_default_arg_in_partial_spec)
2360 << DefArg->getSourceRange();
2361 TTP->setDefaultArgument(0);
2362 DefArg->Destroy(Context);
2363 }
2364 }
2365 }
2366 }
Douglas Gregor88b70942009-02-25 22:02:03 +00002367 }
2368
Douglas Gregorcc636682009-02-17 23:15:12 +00002369 // Check that the specialization uses the same tag kind as the
2370 // original template.
2371 TagDecl::TagKind Kind;
2372 switch (TagSpec) {
2373 default: assert(0 && "Unknown tag type!");
2374 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2375 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2376 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2377 }
Douglas Gregor501c5ce2009-05-14 16:41:31 +00002378 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
2379 Kind, KWLoc,
2380 *ClassTemplate->getIdentifier())) {
Douglas Gregora3a83512009-04-01 23:51:29 +00002381 Diag(KWLoc, diag::err_use_with_wrong_tag)
2382 << ClassTemplate
2383 << CodeModificationHint::CreateReplacement(KWLoc,
2384 ClassTemplate->getTemplatedDecl()->getKindName());
Douglas Gregorcc636682009-02-17 23:15:12 +00002385 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
2386 diag::note_previous_use);
2387 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
2388 }
2389
Douglas Gregor40808ce2009-03-09 23:48:35 +00002390 // Translate the parser's template argument list in our AST format.
2391 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
2392 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
2393
Douglas Gregorcc636682009-02-17 23:15:12 +00002394 // Check that the template argument list is well-formed for this
2395 // template.
Anders Carlssonfb250522009-06-23 01:26:57 +00002396 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
2397 TemplateArgs.size());
Douglas Gregorcc636682009-02-17 23:15:12 +00002398 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
Anders Carlsson6360be72009-06-13 18:20:51 +00002399 TemplateArgs.data(), TemplateArgs.size(),
Douglas Gregor16134c62009-07-01 00:28:38 +00002400 RAngleLoc, false, Converted))
Douglas Gregor212e81c2009-03-25 00:13:59 +00002401 return true;
Douglas Gregorcc636682009-02-17 23:15:12 +00002402
Anders Carlssonfb250522009-06-23 01:26:57 +00002403 assert((Converted.structuredSize() ==
Douglas Gregorcc636682009-02-17 23:15:12 +00002404 ClassTemplate->getTemplateParameters()->size()) &&
2405 "Converted template argument list is too short!");
2406
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002407 // Find the class template (partial) specialization declaration that
Douglas Gregorcc636682009-02-17 23:15:12 +00002408 // corresponds to these arguments.
2409 llvm::FoldingSetNodeID ID;
Douglas Gregorba1ecb52009-06-12 19:43:02 +00002410 if (isPartialSpecialization) {
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002411 bool MirrorsPrimaryTemplate;
Douglas Gregore94866f2009-06-12 21:21:02 +00002412 if (CheckClassTemplatePartialSpecializationArgs(
2413 ClassTemplate->getTemplateParameters(),
Anders Carlssonfb250522009-06-23 01:26:57 +00002414 Converted, MirrorsPrimaryTemplate))
Douglas Gregore94866f2009-06-12 21:21:02 +00002415 return true;
2416
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002417 if (MirrorsPrimaryTemplate) {
2418 // C++ [temp.class.spec]p9b3:
2419 //
2420 // -- The argument list of the specialization shall not be identical
2421 // to the implicit argument list of the primary template.
2422 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
2423 << (TK == TK_Definition)
2424 << CodeModificationHint::CreateRemoval(SourceRange(LAngleLoc,
2425 RAngleLoc));
Douglas Gregorbd1099e2009-07-23 16:36:45 +00002426 return CheckClassTemplate(S, TagSpec, TK, KWLoc, SS,
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002427 ClassTemplate->getIdentifier(),
2428 TemplateNameLoc,
2429 Attr,
2430 move(TemplateParameterLists),
2431 AS_none);
2432 }
2433
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002434 // FIXME: Template parameter list matters, too
Anders Carlsson1c5976e2009-06-05 03:43:12 +00002435 ClassTemplatePartialSpecializationDecl::Profile(ID,
Anders Carlssonfb250522009-06-23 01:26:57 +00002436 Converted.getFlatArguments(),
Douglas Gregor828e2262009-07-29 16:09:57 +00002437 Converted.flatSize(),
2438 Context);
Douglas Gregorba1ecb52009-06-12 19:43:02 +00002439 }
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002440 else
Anders Carlsson1c5976e2009-06-05 03:43:12 +00002441 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlssonfb250522009-06-23 01:26:57 +00002442 Converted.getFlatArguments(),
Douglas Gregor828e2262009-07-29 16:09:57 +00002443 Converted.flatSize(),
2444 Context);
Douglas Gregorcc636682009-02-17 23:15:12 +00002445 void *InsertPos = 0;
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002446 ClassTemplateSpecializationDecl *PrevDecl = 0;
2447
2448 if (isPartialSpecialization)
2449 PrevDecl
2450 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
2451 InsertPos);
2452 else
2453 PrevDecl
2454 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorcc636682009-02-17 23:15:12 +00002455
2456 ClassTemplateSpecializationDecl *Specialization = 0;
2457
Douglas Gregor88b70942009-02-25 22:02:03 +00002458 // Check whether we can declare a class template specialization in
2459 // the current scope.
2460 if (CheckClassTemplateSpecializationScope(ClassTemplate, PrevDecl,
2461 TemplateNameLoc,
Douglas Gregorff668032009-05-13 18:28:20 +00002462 SS.getRange(),
Douglas Gregor16df8502009-06-12 22:21:45 +00002463 isPartialSpecialization,
Douglas Gregorff668032009-05-13 18:28:20 +00002464 /*ExplicitInstantiation=*/false))
Douglas Gregor212e81c2009-03-25 00:13:59 +00002465 return true;
Douglas Gregor88b70942009-02-25 22:02:03 +00002466
Douglas Gregorcc636682009-02-17 23:15:12 +00002467 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
2468 // Since the only prior class template specialization with these
2469 // arguments was referenced but not declared, reuse that
2470 // declaration node as our own, updating its source location to
2471 // reflect our new declaration.
Douglas Gregorcc636682009-02-17 23:15:12 +00002472 Specialization = PrevDecl;
Douglas Gregor6bc9f7e2009-02-25 22:18:32 +00002473 Specialization->setLocation(TemplateNameLoc);
Douglas Gregorcc636682009-02-17 23:15:12 +00002474 PrevDecl = 0;
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002475 } else if (isPartialSpecialization) {
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002476 // Create a new class template partial specialization declaration node.
2477 TemplateParameterList *TemplateParams
2478 = static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
2479 ClassTemplatePartialSpecializationDecl *PrevPartial
2480 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
2481 ClassTemplatePartialSpecializationDecl *Partial
2482 = ClassTemplatePartialSpecializationDecl::Create(Context,
2483 ClassTemplate->getDeclContext(),
Anders Carlsson91fdf6f2009-06-05 04:06:48 +00002484 TemplateNameLoc,
2485 TemplateParams,
2486 ClassTemplate,
Anders Carlssonfb250522009-06-23 01:26:57 +00002487 Converted,
Anders Carlsson91fdf6f2009-06-05 04:06:48 +00002488 PrevPartial);
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002489
2490 if (PrevPartial) {
2491 ClassTemplate->getPartialSpecializations().RemoveNode(PrevPartial);
2492 ClassTemplate->getPartialSpecializations().GetOrInsertNode(Partial);
2493 } else {
2494 ClassTemplate->getPartialSpecializations().InsertNode(Partial, InsertPos);
2495 }
2496 Specialization = Partial;
Douglas Gregor031a5882009-06-13 00:26:55 +00002497
2498 // Check that all of the template parameters of the class template
2499 // partial specialization are deducible from the template
2500 // arguments. If not, this class template partial specialization
2501 // will never be used.
2502 llvm::SmallVector<bool, 8> DeducibleParams;
2503 DeducibleParams.resize(TemplateParams->size());
2504 MarkDeducedTemplateParameters(Partial->getTemplateArgs(), DeducibleParams);
2505 unsigned NumNonDeducible = 0;
2506 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I)
2507 if (!DeducibleParams[I])
2508 ++NumNonDeducible;
2509
2510 if (NumNonDeducible) {
2511 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
2512 << (NumNonDeducible > 1)
2513 << SourceRange(TemplateNameLoc, RAngleLoc);
2514 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
2515 if (!DeducibleParams[I]) {
2516 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
2517 if (Param->getDeclName())
2518 Diag(Param->getLocation(),
2519 diag::note_partial_spec_unused_parameter)
2520 << Param->getDeclName();
2521 else
2522 Diag(Param->getLocation(),
2523 diag::note_partial_spec_unused_parameter)
2524 << std::string("<anonymous>");
2525 }
2526 }
2527 }
2528
Douglas Gregorcc636682009-02-17 23:15:12 +00002529 } else {
2530 // Create a new class template specialization declaration node for
2531 // this explicit specialization.
2532 Specialization
2533 = ClassTemplateSpecializationDecl::Create(Context,
2534 ClassTemplate->getDeclContext(),
2535 TemplateNameLoc,
Anders Carlsson91fdf6f2009-06-05 04:06:48 +00002536 ClassTemplate,
Anders Carlssonfb250522009-06-23 01:26:57 +00002537 Converted,
Douglas Gregorcc636682009-02-17 23:15:12 +00002538 PrevDecl);
2539
2540 if (PrevDecl) {
2541 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
2542 ClassTemplate->getSpecializations().GetOrInsertNode(Specialization);
2543 } else {
2544 ClassTemplate->getSpecializations().InsertNode(Specialization,
2545 InsertPos);
2546 }
2547 }
2548
2549 // Note that this is an explicit specialization.
2550 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
2551
2552 // Check that this isn't a redefinition of this specialization.
2553 if (TK == TK_Definition) {
2554 if (RecordDecl *Def = Specialization->getDefinition(Context)) {
Mike Stump390b4cc2009-05-16 07:39:55 +00002555 // FIXME: Should also handle explicit specialization after implicit
2556 // instantiation with a special diagnostic.
Douglas Gregorcc636682009-02-17 23:15:12 +00002557 SourceRange Range(TemplateNameLoc, RAngleLoc);
2558 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002559 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregorcc636682009-02-17 23:15:12 +00002560 Diag(Def->getLocation(), diag::note_previous_definition);
2561 Specialization->setInvalidDecl();
Douglas Gregor212e81c2009-03-25 00:13:59 +00002562 return true;
Douglas Gregorcc636682009-02-17 23:15:12 +00002563 }
2564 }
2565
Douglas Gregorfc705b82009-02-26 22:19:44 +00002566 // Build the fully-sugared type for this class template
2567 // specialization as the user wrote in the specialization
2568 // itself. This means that we'll pretty-print the type retrieved
2569 // from the specialization's declaration the way that the user
2570 // actually wrote the specialization, rather than formatting the
2571 // name based on the "canonical" representation used to store the
2572 // template arguments in the specialization.
Douglas Gregore6258932009-03-19 00:39:20 +00002573 QualType WrittenTy
Douglas Gregor7532dc62009-03-30 22:58:21 +00002574 = Context.getTemplateSpecializationType(Name,
Anders Carlsson6360be72009-06-13 18:20:51 +00002575 TemplateArgs.data(),
Douglas Gregor7532dc62009-03-30 22:58:21 +00002576 TemplateArgs.size(),
Douglas Gregore6258932009-03-19 00:39:20 +00002577 Context.getTypeDeclType(Specialization));
Douglas Gregor7532dc62009-03-30 22:58:21 +00002578 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregor40808ce2009-03-09 23:48:35 +00002579 TemplateArgsIn.release();
Douglas Gregorcc636682009-02-17 23:15:12 +00002580
Douglas Gregor6bc9f7e2009-02-25 22:18:32 +00002581 // C++ [temp.expl.spec]p9:
2582 // A template explicit specialization is in the scope of the
2583 // namespace in which the template was defined.
2584 //
2585 // We actually implement this paragraph where we set the semantic
2586 // context (in the creation of the ClassTemplateSpecializationDecl),
2587 // but we also maintain the lexical context where the actual
2588 // definition occurs.
Douglas Gregorcc636682009-02-17 23:15:12 +00002589 Specialization->setLexicalDeclContext(CurContext);
2590
2591 // We may be starting the definition of this specialization.
2592 if (TK == TK_Definition)
2593 Specialization->startDefinition();
2594
2595 // Add the specialization into its lexical context, so that it can
2596 // be seen when iterating through the list of declarations in that
2597 // context. However, specializations are not found by name lookup.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002598 CurContext->addDecl(Specialization);
Chris Lattnerb28317a2009-03-28 19:18:32 +00002599 return DeclPtrTy::make(Specialization);
Douglas Gregorcc636682009-02-17 23:15:12 +00002600}
Douglas Gregord57959a2009-03-27 23:10:48 +00002601
Douglas Gregore542c862009-06-23 23:11:28 +00002602Sema::DeclPtrTy
2603Sema::ActOnTemplateDeclarator(Scope *S,
2604 MultiTemplateParamsArg TemplateParameterLists,
2605 Declarator &D) {
2606 return HandleDeclarator(S, D, move(TemplateParameterLists), false);
2607}
2608
Douglas Gregor52591bf2009-06-24 00:54:41 +00002609Sema::DeclPtrTy
2610Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
2611 MultiTemplateParamsArg TemplateParameterLists,
2612 Declarator &D) {
2613 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
2614 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
2615 "Not a function declarator!");
2616 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2617
2618 if (FTI.hasPrototype) {
2619 // FIXME: Diagnose arguments without names in C.
2620 }
2621
2622 Scope *ParentScope = FnBodyScope->getParent();
2623
2624 DeclPtrTy DP = HandleDeclarator(ParentScope, D,
2625 move(TemplateParameterLists),
2626 /*IsFunctionDefinition=*/true);
Douglas Gregorf59a56e2009-07-21 23:53:31 +00002627 if (FunctionTemplateDecl *FunctionTemplate
2628 = dyn_cast_or_null<FunctionTemplateDecl>(DP.getAs<Decl>()))
Douglas Gregore53060f2009-06-25 22:08:12 +00002629 return ActOnStartOfFunctionDef(FnBodyScope,
2630 DeclPtrTy::make(FunctionTemplate->getTemplatedDecl()));
Douglas Gregorf59a56e2009-07-21 23:53:31 +00002631 if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(DP.getAs<Decl>()))
2632 return ActOnStartOfFunctionDef(FnBodyScope, DeclPtrTy::make(Function));
Douglas Gregore53060f2009-06-25 22:08:12 +00002633 return DeclPtrTy();
Douglas Gregor52591bf2009-06-24 00:54:41 +00002634}
2635
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002636// Explicit instantiation of a class template specialization
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002637Sema::DeclResult
2638Sema::ActOnExplicitInstantiation(Scope *S, SourceLocation TemplateLoc,
2639 unsigned TagSpec,
2640 SourceLocation KWLoc,
2641 const CXXScopeSpec &SS,
2642 TemplateTy TemplateD,
2643 SourceLocation TemplateNameLoc,
2644 SourceLocation LAngleLoc,
2645 ASTTemplateArgsPtr TemplateArgsIn,
2646 SourceLocation *TemplateArgLocs,
2647 SourceLocation RAngleLoc,
2648 AttributeList *Attr) {
2649 // Find the class template we're specializing
2650 TemplateName Name = TemplateD.getAsVal<TemplateName>();
2651 ClassTemplateDecl *ClassTemplate
2652 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
2653
2654 // Check that the specialization uses the same tag kind as the
2655 // original template.
2656 TagDecl::TagKind Kind;
2657 switch (TagSpec) {
2658 default: assert(0 && "Unknown tag type!");
2659 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2660 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2661 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2662 }
Douglas Gregor501c5ce2009-05-14 16:41:31 +00002663 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
2664 Kind, KWLoc,
2665 *ClassTemplate->getIdentifier())) {
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002666 Diag(KWLoc, diag::err_use_with_wrong_tag)
2667 << ClassTemplate
2668 << CodeModificationHint::CreateReplacement(KWLoc,
2669 ClassTemplate->getTemplatedDecl()->getKindName());
2670 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
2671 diag::note_previous_use);
2672 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
2673 }
2674
Douglas Gregorff668032009-05-13 18:28:20 +00002675 // C++0x [temp.explicit]p2:
2676 // [...] An explicit instantiation shall appear in an enclosing
2677 // namespace of its template. [...]
2678 //
2679 // This is C++ DR 275.
2680 if (CheckClassTemplateSpecializationScope(ClassTemplate, 0,
2681 TemplateNameLoc,
2682 SS.getRange(),
Douglas Gregor16df8502009-06-12 22:21:45 +00002683 /*PartialSpecialization=*/false,
Douglas Gregorff668032009-05-13 18:28:20 +00002684 /*ExplicitInstantiation=*/true))
2685 return true;
2686
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002687 // Translate the parser's template argument list in our AST format.
2688 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
2689 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
2690
2691 // Check that the template argument list is well-formed for this
2692 // template.
Anders Carlssonfb250522009-06-23 01:26:57 +00002693 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
2694 TemplateArgs.size());
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002695 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
Anders Carlsson9bff9a92009-06-05 02:12:32 +00002696 TemplateArgs.data(), TemplateArgs.size(),
Douglas Gregor16134c62009-07-01 00:28:38 +00002697 RAngleLoc, false, Converted))
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002698 return true;
2699
Anders Carlssonfb250522009-06-23 01:26:57 +00002700 assert((Converted.structuredSize() ==
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002701 ClassTemplate->getTemplateParameters()->size()) &&
2702 "Converted template argument list is too short!");
2703
2704 // Find the class template specialization declaration that
2705 // corresponds to these arguments.
2706 llvm::FoldingSetNodeID ID;
Anders Carlsson1c5976e2009-06-05 03:43:12 +00002707 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlssonfb250522009-06-23 01:26:57 +00002708 Converted.getFlatArguments(),
Douglas Gregor828e2262009-07-29 16:09:57 +00002709 Converted.flatSize(),
2710 Context);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002711 void *InsertPos = 0;
2712 ClassTemplateSpecializationDecl *PrevDecl
2713 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
2714
2715 ClassTemplateSpecializationDecl *Specialization = 0;
2716
Douglas Gregorff668032009-05-13 18:28:20 +00002717 bool SpecializationRequiresInstantiation = true;
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002718 if (PrevDecl) {
Douglas Gregorff668032009-05-13 18:28:20 +00002719 if (PrevDecl->getSpecializationKind() == TSK_ExplicitInstantiation) {
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002720 // This particular specialization has already been declared or
2721 // instantiated. We cannot explicitly instantiate it.
Douglas Gregorff668032009-05-13 18:28:20 +00002722 Diag(TemplateNameLoc, diag::err_explicit_instantiation_duplicate)
2723 << Context.getTypeDeclType(PrevDecl);
2724 Diag(PrevDecl->getLocation(),
2725 diag::note_previous_explicit_instantiation);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002726 return DeclPtrTy::make(PrevDecl);
2727 }
2728
Douglas Gregorff668032009-05-13 18:28:20 +00002729 if (PrevDecl->getSpecializationKind() == TSK_ExplicitSpecialization) {
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002730 // C++ DR 259, C++0x [temp.explicit]p4:
Douglas Gregorff668032009-05-13 18:28:20 +00002731 // For a given set of template parameters, if an explicit
2732 // instantiation of a template appears after a declaration of
2733 // an explicit specialization for that template, the explicit
2734 // instantiation has no effect.
2735 if (!getLangOptions().CPlusPlus0x) {
2736 Diag(TemplateNameLoc,
2737 diag::ext_explicit_instantiation_after_specialization)
2738 << Context.getTypeDeclType(PrevDecl);
2739 Diag(PrevDecl->getLocation(),
2740 diag::note_previous_template_specialization);
2741 }
2742
2743 // Create a new class template specialization declaration node
2744 // for this explicit specialization. This node is only used to
2745 // record the existence of this explicit instantiation for
2746 // accurate reproduction of the source code; we don't actually
2747 // use it for anything, since it is semantically irrelevant.
2748 Specialization
2749 = ClassTemplateSpecializationDecl::Create(Context,
2750 ClassTemplate->getDeclContext(),
2751 TemplateNameLoc,
2752 ClassTemplate,
Anders Carlssonfb250522009-06-23 01:26:57 +00002753 Converted, 0);
Douglas Gregorff668032009-05-13 18:28:20 +00002754 Specialization->setLexicalDeclContext(CurContext);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002755 CurContext->addDecl(Specialization);
Douglas Gregorff668032009-05-13 18:28:20 +00002756 return DeclPtrTy::make(Specialization);
2757 }
2758
2759 // If we have already (implicitly) instantiated this
2760 // specialization, there is less work to do.
2761 if (PrevDecl->getSpecializationKind() == TSK_ImplicitInstantiation)
2762 SpecializationRequiresInstantiation = false;
2763
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002764 // Since the only prior class template specialization with these
2765 // arguments was referenced but not declared, reuse that
2766 // declaration node as our own, updating its source location to
2767 // reflect our new declaration.
2768 Specialization = PrevDecl;
2769 Specialization->setLocation(TemplateNameLoc);
2770 PrevDecl = 0;
2771 } else {
2772 // Create a new class template specialization declaration node for
2773 // this explicit specialization.
2774 Specialization
2775 = ClassTemplateSpecializationDecl::Create(Context,
2776 ClassTemplate->getDeclContext(),
2777 TemplateNameLoc,
2778 ClassTemplate,
Anders Carlssonfb250522009-06-23 01:26:57 +00002779 Converted, 0);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002780
2781 ClassTemplate->getSpecializations().InsertNode(Specialization,
2782 InsertPos);
2783 }
2784
2785 // Build the fully-sugared type for this explicit instantiation as
2786 // the user wrote in the explicit instantiation itself. This means
2787 // that we'll pretty-print the type retrieved from the
2788 // specialization's declaration the way that the user actually wrote
2789 // the explicit instantiation, rather than formatting the name based
2790 // on the "canonical" representation used to store the template
2791 // arguments in the specialization.
2792 QualType WrittenTy
2793 = Context.getTemplateSpecializationType(Name,
Anders Carlssonf4e2a2c2009-06-05 02:45:24 +00002794 TemplateArgs.data(),
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002795 TemplateArgs.size(),
2796 Context.getTypeDeclType(Specialization));
2797 Specialization->setTypeAsWritten(WrittenTy);
2798 TemplateArgsIn.release();
2799
2800 // Add the explicit instantiation into its lexical context. However,
2801 // since explicit instantiations are never found by name lookup, we
2802 // just put it into the declaration context directly.
2803 Specialization->setLexicalDeclContext(CurContext);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002804 CurContext->addDecl(Specialization);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002805
2806 // C++ [temp.explicit]p3:
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002807 // A definition of a class template or class member template
2808 // shall be in scope at the point of the explicit instantiation of
2809 // the class template or class member template.
2810 //
2811 // This check comes when we actually try to perform the
2812 // instantiation.
Douglas Gregore2c31ff2009-05-15 17:59:04 +00002813 if (SpecializationRequiresInstantiation)
2814 InstantiateClassTemplateSpecialization(Specialization, true);
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00002815 else // Instantiate the members of this class template specialization.
Douglas Gregore2c31ff2009-05-15 17:59:04 +00002816 InstantiateClassTemplateSpecializationMembers(TemplateLoc, Specialization);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002817
2818 return DeclPtrTy::make(Specialization);
2819}
2820
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002821// Explicit instantiation of a member class of a class template.
2822Sema::DeclResult
2823Sema::ActOnExplicitInstantiation(Scope *S, SourceLocation TemplateLoc,
2824 unsigned TagSpec,
2825 SourceLocation KWLoc,
2826 const CXXScopeSpec &SS,
2827 IdentifierInfo *Name,
2828 SourceLocation NameLoc,
2829 AttributeList *Attr) {
2830
Douglas Gregor402abb52009-05-28 23:31:59 +00002831 bool Owned = false;
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002832 DeclPtrTy TagD = ActOnTag(S, TagSpec, Action::TK_Reference,
Douglas Gregor7cdbc582009-07-22 23:48:44 +00002833 KWLoc, SS, Name, NameLoc, Attr, AS_none,
2834 MultiTemplateParamsArg(*this, 0, 0), Owned);
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002835 if (!TagD)
2836 return true;
2837
2838 TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
2839 if (Tag->isEnum()) {
2840 Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
2841 << Context.getTypeDeclType(Tag);
2842 return true;
2843 }
2844
Douglas Gregord0c87372009-05-27 17:30:49 +00002845 if (Tag->isInvalidDecl())
2846 return true;
2847
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002848 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
2849 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
2850 if (!Pattern) {
2851 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
2852 << Context.getTypeDeclType(Record);
2853 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
2854 return true;
2855 }
2856
2857 // C++0x [temp.explicit]p2:
2858 // [...] An explicit instantiation shall appear in an enclosing
2859 // namespace of its template. [...]
2860 //
2861 // This is C++ DR 275.
2862 if (getLangOptions().CPlusPlus0x) {
Mike Stump390b4cc2009-05-16 07:39:55 +00002863 // FIXME: In C++98, we would like to turn these errors into warnings,
2864 // dependent on a -Wc++0x flag.
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002865 DeclContext *PatternContext
2866 = Pattern->getDeclContext()->getEnclosingNamespaceContext();
2867 if (!CurContext->Encloses(PatternContext)) {
2868 Diag(TemplateLoc, diag::err_explicit_instantiation_out_of_scope)
2869 << Record << cast<NamedDecl>(PatternContext) << SS.getRange();
2870 Diag(Pattern->getLocation(), diag::note_previous_declaration);
2871 }
2872 }
2873
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002874 if (!Record->getDefinition(Context)) {
2875 // If the class has a definition, instantiate it (and all of its
2876 // members, recursively).
2877 Pattern = cast_or_null<CXXRecordDecl>(Pattern->getDefinition(Context));
2878 if (Pattern && InstantiateClass(TemplateLoc, Record, Pattern,
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002879 getTemplateInstantiationArgs(Record),
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002880 /*ExplicitInstantiation=*/true))
2881 return true;
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00002882 } else // Instantiate all of the members of class.
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002883 InstantiateClassMembers(TemplateLoc, Record,
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002884 getTemplateInstantiationArgs(Record));
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002885
Mike Stump390b4cc2009-05-16 07:39:55 +00002886 // FIXME: We don't have any representation for explicit instantiations of
2887 // member classes. Such a representation is not needed for compilation, but it
2888 // should be available for clients that want to see all of the declarations in
2889 // the source code.
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002890 return TagD;
2891}
2892
Douglas Gregord57959a2009-03-27 23:10:48 +00002893Sema::TypeResult
2894Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
2895 const IdentifierInfo &II, SourceLocation IdLoc) {
2896 NestedNameSpecifier *NNS
2897 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
2898 if (!NNS)
2899 return true;
2900
2901 QualType T = CheckTypenameType(NNS, II, SourceRange(TypenameLoc, IdLoc));
Douglas Gregor31a19b62009-04-01 21:51:26 +00002902 if (T.isNull())
2903 return true;
Douglas Gregord57959a2009-03-27 23:10:48 +00002904 return T.getAsOpaquePtr();
2905}
2906
Douglas Gregor17343172009-04-01 00:28:59 +00002907Sema::TypeResult
2908Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
2909 SourceLocation TemplateLoc, TypeTy *Ty) {
2910 QualType T = QualType::getFromOpaquePtr(Ty);
2911 NestedNameSpecifier *NNS
2912 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
2913 const TemplateSpecializationType *TemplateId
2914 = T->getAsTemplateSpecializationType();
2915 assert(TemplateId && "Expected a template specialization type");
2916
2917 if (NNS->isDependent())
2918 return Context.getTypenameType(NNS, TemplateId).getAsOpaquePtr();
2919
2920 return Context.getQualifiedNameType(NNS, T).getAsOpaquePtr();
2921}
2922
Douglas Gregord57959a2009-03-27 23:10:48 +00002923/// \brief Build the type that describes a C++ typename specifier,
2924/// e.g., "typename T::type".
2925QualType
2926Sema::CheckTypenameType(NestedNameSpecifier *NNS, const IdentifierInfo &II,
2927 SourceRange Range) {
Douglas Gregor42af25f2009-05-11 19:58:34 +00002928 CXXRecordDecl *CurrentInstantiation = 0;
2929 if (NNS->isDependent()) {
2930 CurrentInstantiation = getCurrentInstantiationOf(NNS);
Douglas Gregord57959a2009-03-27 23:10:48 +00002931
Douglas Gregor42af25f2009-05-11 19:58:34 +00002932 // If the nested-name-specifier does not refer to the current
2933 // instantiation, then build a typename type.
2934 if (!CurrentInstantiation)
2935 return Context.getTypenameType(NNS, &II);
2936 }
Douglas Gregord57959a2009-03-27 23:10:48 +00002937
Douglas Gregor42af25f2009-05-11 19:58:34 +00002938 DeclContext *Ctx = 0;
2939
2940 if (CurrentInstantiation)
2941 Ctx = CurrentInstantiation;
2942 else {
2943 CXXScopeSpec SS;
2944 SS.setScopeRep(NNS);
2945 SS.setRange(Range);
2946 if (RequireCompleteDeclContext(SS))
2947 return QualType();
2948
2949 Ctx = computeDeclContext(SS);
2950 }
Douglas Gregord57959a2009-03-27 23:10:48 +00002951 assert(Ctx && "No declaration context?");
2952
2953 DeclarationName Name(&II);
2954 LookupResult Result = LookupQualifiedName(Ctx, Name, LookupOrdinaryName,
2955 false);
2956 unsigned DiagID = 0;
2957 Decl *Referenced = 0;
2958 switch (Result.getKind()) {
2959 case LookupResult::NotFound:
2960 if (Ctx->isTranslationUnit())
2961 DiagID = diag::err_typename_nested_not_found_global;
2962 else
2963 DiagID = diag::err_typename_nested_not_found;
2964 break;
2965
2966 case LookupResult::Found:
2967 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getAsDecl())) {
2968 // We found a type. Build a QualifiedNameType, since the
2969 // typename-specifier was just sugar. FIXME: Tell
2970 // QualifiedNameType that it has a "typename" prefix.
2971 return Context.getQualifiedNameType(NNS, Context.getTypeDeclType(Type));
2972 }
2973
2974 DiagID = diag::err_typename_nested_not_type;
2975 Referenced = Result.getAsDecl();
2976 break;
2977
2978 case LookupResult::FoundOverloaded:
2979 DiagID = diag::err_typename_nested_not_type;
2980 Referenced = *Result.begin();
2981 break;
2982
2983 case LookupResult::AmbiguousBaseSubobjectTypes:
2984 case LookupResult::AmbiguousBaseSubobjects:
2985 case LookupResult::AmbiguousReference:
2986 DiagnoseAmbiguousLookup(Result, Name, Range.getEnd(), Range);
2987 return QualType();
2988 }
2989
2990 // If we get here, it's because name lookup did not find a
2991 // type. Emit an appropriate diagnostic and return an error.
2992 if (NamedDecl *NamedCtx = dyn_cast<NamedDecl>(Ctx))
2993 Diag(Range.getEnd(), DiagID) << Range << Name << NamedCtx;
2994 else
2995 Diag(Range.getEnd(), DiagID) << Range << Name;
2996 if (Referenced)
2997 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
2998 << Name;
2999 return QualType();
3000}