blob: d72cea0907104362c2fbf9680ec66007921ac2be [file] [log] [blame]
Douglas Gregor72c3f312008-12-05 18:15:24 +00001//===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===/
Douglas Gregor72c3f312008-12-05 18:15:24 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Douglas Gregor99ebf652009-02-27 19:31:52 +00007//===----------------------------------------------------------------------===/
Douglas Gregor72c3f312008-12-05 18:15:24 +00008//
9// This file implements semantic analysis for C++ templates.
Douglas Gregor99ebf652009-02-27 19:31:52 +000010//===----------------------------------------------------------------------===/
Douglas Gregor72c3f312008-12-05 18:15:24 +000011
12#include "Sema.h"
Douglas Gregor4a959d82009-08-06 16:20:37 +000013#include "TreeTransform.h"
Douglas Gregorddc29e12009-02-06 22:42:48 +000014#include "clang/AST/ASTContext.h"
Douglas Gregor898574e2008-12-05 23:32:09 +000015#include "clang/AST/Expr.h"
Douglas Gregorcc45cb32009-02-11 19:52:55 +000016#include "clang/AST/ExprCXX.h"
Douglas Gregoraaba5e32009-02-04 19:02:06 +000017#include "clang/AST/DeclTemplate.h"
Douglas Gregor72c3f312008-12-05 18:15:24 +000018#include "clang/Parse/DeclSpec.h"
19#include "clang/Basic/LangOptions.h"
Douglas Gregor4a959d82009-08-06 16:20:37 +000020#include "llvm/Support/Compiler.h"
Douglas Gregor72c3f312008-12-05 18:15:24 +000021
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 Gregor495c35d2009-08-25 22:51:20 +000030 const CXXScopeSpec *SS,
31 bool EnteringContext,
32 TemplateTy &TemplateResult) {
33 LookupResult Found = LookupParsedName(S, SS, &II, LookupOrdinaryName,
34 false, false, SourceLocation(),
35 EnteringContext);
36
37 // FIXME: Cope with ambiguous name-lookup results.
38 assert(!Found.isAmbiguous() &&
39 "Cannot handle template name-lookup ambiguities");
40
41 NamedDecl *IIDecl = Found;
42
Douglas Gregor7532dc62009-03-30 22:58:21 +000043 TemplateNameKind TNK = TNK_Non_template;
44 TemplateDecl *Template = 0;
45
Douglas Gregord6fb7ef2008-12-18 19:37:40 +000046 if (IIDecl) {
Douglas Gregor7532dc62009-03-30 22:58:21 +000047 if ((Template = dyn_cast<TemplateDecl>(IIDecl))) {
Douglas Gregor55f6b142009-02-09 18:46:07 +000048 if (isa<FunctionTemplateDecl>(IIDecl))
Douglas Gregor7532dc62009-03-30 22:58:21 +000049 TNK = TNK_Function_template;
Douglas Gregorc45c2322009-03-31 00:43:58 +000050 else if (isa<ClassTemplateDecl>(IIDecl) ||
51 isa<TemplateTemplateParmDecl>(IIDecl))
52 TNK = TNK_Type_template;
Douglas Gregor7532dc62009-03-30 22:58:21 +000053 else
54 assert(false && "Unknown template declaration kind");
Douglas Gregorbefc20e2009-03-26 00:10:35 +000055 } else if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(IIDecl)) {
56 // C++ [temp.local]p1:
57 // Like normal (non-template) classes, class templates have an
58 // injected-class-name (Clause 9). The injected-class-name
59 // can be used with or without a template-argument-list. When
60 // it is used without a template-argument-list, it is
61 // equivalent to the injected-class-name followed by the
62 // template-parameters of the class template enclosed in
63 // <>. When it is used with a template-argument-list, it
64 // refers to the specified class template specialization,
65 // which could be the current specialization or another
66 // specialization.
67 if (Record->isInjectedClassName()) {
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +000068 Record = cast<CXXRecordDecl>(Record->getCanonicalDecl());
Douglas Gregor7532dc62009-03-30 22:58:21 +000069 if ((Template = Record->getDescribedClassTemplate()))
Douglas Gregorc45c2322009-03-31 00:43:58 +000070 TNK = TNK_Type_template;
Douglas Gregor7532dc62009-03-30 22:58:21 +000071 else if (ClassTemplateSpecializationDecl *Spec
Douglas Gregorbefc20e2009-03-26 00:10:35 +000072 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
Douglas Gregor7532dc62009-03-30 22:58:21 +000073 Template = Spec->getSpecializedTemplate();
Douglas Gregorc45c2322009-03-31 00:43:58 +000074 TNK = TNK_Type_template;
Douglas Gregorbefc20e2009-03-26 00:10:35 +000075 }
76 }
Douglas Gregorf511e472009-07-29 16:56:42 +000077 } else if (OverloadedFunctionDecl *Ovl
78 = dyn_cast<OverloadedFunctionDecl>(IIDecl)) {
Douglas Gregord6fb7ef2008-12-18 19:37:40 +000079 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
80 FEnd = Ovl->function_end();
81 F != FEnd; ++F) {
Douglas Gregorf511e472009-07-29 16:56:42 +000082 if (FunctionTemplateDecl *FuncTmpl
83 = dyn_cast<FunctionTemplateDecl>(*F)) {
84 // We've found a function template. Determine whether there are
85 // any other function templates we need to bundle together in an
86 // OverloadedFunctionDecl
87 for (++F; F != FEnd; ++F) {
88 if (isa<FunctionTemplateDecl>(*F))
89 break;
90 }
91
92 if (F != FEnd) {
93 // Build an overloaded function decl containing only the
94 // function templates in Ovl.
95 OverloadedFunctionDecl *OvlTemplate
96 = OverloadedFunctionDecl::Create(Context,
97 Ovl->getDeclContext(),
98 Ovl->getDeclName());
99 OvlTemplate->addOverload(FuncTmpl);
100 OvlTemplate->addOverload(*F);
101 for (++F; F != FEnd; ++F) {
102 if (isa<FunctionTemplateDecl>(*F))
103 OvlTemplate->addOverload(*F);
104 }
Douglas Gregord99cbe62009-07-29 18:26:50 +0000105
106 // Form the resulting TemplateName
107 if (SS && SS->isSet() && !SS->isInvalid()) {
108 NestedNameSpecifier *Qualifier
109 = static_cast<NestedNameSpecifier *>(SS->getScopeRep());
110 TemplateResult
111 = TemplateTy::make(Context.getQualifiedTemplateName(Qualifier,
112 false,
113 OvlTemplate));
114 } else {
115 TemplateResult = TemplateTy::make(TemplateName(OvlTemplate));
116 }
Douglas Gregorf511e472009-07-29 16:56:42 +0000117 return TNK_Function_template;
118 }
119
120 TNK = TNK_Function_template;
121 Template = FuncTmpl;
122 break;
Douglas Gregor55f6b142009-02-09 18:46:07 +0000123 }
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000124 }
125 }
Douglas Gregor7532dc62009-03-30 22:58:21 +0000126
127 if (TNK != TNK_Non_template) {
128 if (SS && SS->isSet() && !SS->isInvalid()) {
129 NestedNameSpecifier *Qualifier
130 = static_cast<NestedNameSpecifier *>(SS->getScopeRep());
131 TemplateResult
132 = TemplateTy::make(Context.getQualifiedTemplateName(Qualifier,
133 false,
134 Template));
135 } else
136 TemplateResult = TemplateTy::make(TemplateName(Template));
137 }
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000138 }
Douglas Gregor7532dc62009-03-30 22:58:21 +0000139 return TNK;
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000140}
141
Douglas Gregor72c3f312008-12-05 18:15:24 +0000142/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
143/// that the template parameter 'PrevDecl' is being shadowed by a new
144/// declaration at location Loc. Returns true to indicate that this is
145/// an error, and false otherwise.
146bool Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
Douglas Gregorf57172b2008-12-08 18:40:42 +0000147 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregor72c3f312008-12-05 18:15:24 +0000148
149 // Microsoft Visual C++ permits template parameters to be shadowed.
150 if (getLangOptions().Microsoft)
151 return false;
152
153 // C++ [temp.local]p4:
154 // A template-parameter shall not be redeclared within its
155 // scope (including nested scopes).
156 Diag(Loc, diag::err_template_param_shadow)
157 << cast<NamedDecl>(PrevDecl)->getDeclName();
158 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
159 return true;
160}
161
Douglas Gregor2943aed2009-03-03 04:44:36 +0000162/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000163/// the parameter D to reference the templated declaration and return a pointer
164/// to the template declaration. Otherwise, do nothing to D and return null.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000165TemplateDecl *Sema::AdjustDeclIfTemplate(DeclPtrTy &D) {
166 if (TemplateDecl *Temp = dyn_cast<TemplateDecl>(D.getAs<Decl>())) {
167 D = DeclPtrTy::make(Temp->getTemplatedDecl());
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000168 return Temp;
169 }
170 return 0;
171}
172
Douglas Gregor72c3f312008-12-05 18:15:24 +0000173/// ActOnTypeParameter - Called when a C++ template type parameter
174/// (e.g., "typename T") has been parsed. Typename specifies whether
175/// the keyword "typename" was used to declare the type parameter
176/// (otherwise, "class" was used), and KeyLoc is the location of the
177/// "class" or "typename" keyword. ParamName is the name of the
178/// parameter (NULL indicates an unnamed template parameter) and
179/// ParamName is the location of the parameter name (if any).
180/// If the type parameter has a default argument, it will be added
181/// later via ActOnTypeParameterDefault.
Anders Carlsson941df7d2009-06-12 19:58:00 +0000182Sema::DeclPtrTy Sema::ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis,
183 SourceLocation EllipsisLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +0000184 SourceLocation KeyLoc,
185 IdentifierInfo *ParamName,
186 SourceLocation ParamNameLoc,
187 unsigned Depth, unsigned Position) {
Douglas Gregor72c3f312008-12-05 18:15:24 +0000188 assert(S->isTemplateParamScope() &&
189 "Template type parameter not in template parameter scope!");
190 bool Invalid = false;
191
192 if (ParamName) {
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000193 NamedDecl *PrevDecl = LookupName(S, ParamName, LookupTagName);
Douglas Gregorf57172b2008-12-08 18:40:42 +0000194 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor72c3f312008-12-05 18:15:24 +0000195 Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc,
196 PrevDecl);
197 }
198
Douglas Gregorddc29e12009-02-06 22:42:48 +0000199 SourceLocation Loc = ParamNameLoc;
200 if (!ParamName)
201 Loc = KeyLoc;
202
Douglas Gregor72c3f312008-12-05 18:15:24 +0000203 TemplateTypeParmDecl *Param
Douglas Gregorddc29e12009-02-06 22:42:48 +0000204 = TemplateTypeParmDecl::Create(Context, CurContext, Loc,
Anders Carlsson6d845ae2009-06-12 22:23:22 +0000205 Depth, Position, ParamName, Typename,
206 Ellipsis);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000207 if (Invalid)
208 Param->setInvalidDecl();
209
210 if (ParamName) {
211 // Add the template parameter into the current scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000212 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor72c3f312008-12-05 18:15:24 +0000213 IdResolver.AddDecl(Param);
214 }
215
Chris Lattnerb28317a2009-03-28 19:18:32 +0000216 return DeclPtrTy::make(Param);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000217}
218
Douglas Gregord684b002009-02-10 19:49:53 +0000219/// ActOnTypeParameterDefault - Adds a default argument (the type
220/// Default) to the given template type parameter (TypeParam).
Chris Lattnerb28317a2009-03-28 19:18:32 +0000221void Sema::ActOnTypeParameterDefault(DeclPtrTy TypeParam,
Douglas Gregord684b002009-02-10 19:49:53 +0000222 SourceLocation EqualLoc,
223 SourceLocation DefaultLoc,
224 TypeTy *DefaultT) {
225 TemplateTypeParmDecl *Parm
Chris Lattnerb28317a2009-03-28 19:18:32 +0000226 = cast<TemplateTypeParmDecl>(TypeParam.getAs<Decl>());
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000227 // FIXME: Preserve type source info.
228 QualType Default = GetTypeFromParser(DefaultT);
Douglas Gregord684b002009-02-10 19:49:53 +0000229
Anders Carlsson9c4c5c82009-06-12 22:30:13 +0000230 // C++0x [temp.param]p9:
231 // A default template-argument may be specified for any kind of
232 // template-parameter that is not a template parameter pack.
233 if (Parm->isParameterPack()) {
234 Diag(DefaultLoc, diag::err_template_param_pack_default_arg);
Anders Carlsson9c4c5c82009-06-12 22:30:13 +0000235 return;
236 }
237
Douglas Gregord684b002009-02-10 19:49:53 +0000238 // C++ [temp.param]p14:
239 // A template-parameter shall not be used in its own default argument.
240 // FIXME: Implement this check! Needs a recursive walk over the types.
241
242 // Check the template argument itself.
243 if (CheckTemplateArgument(Parm, Default, DefaultLoc)) {
244 Parm->setInvalidDecl();
245 return;
246 }
247
248 Parm->setDefaultArgument(Default, DefaultLoc, false);
249}
250
Douglas Gregor2943aed2009-03-03 04:44:36 +0000251/// \brief Check that the type of a non-type template parameter is
252/// well-formed.
253///
254/// \returns the (possibly-promoted) parameter type if valid;
255/// otherwise, produces a diagnostic and returns a NULL type.
256QualType
257Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
258 // C++ [temp.param]p4:
259 //
260 // A non-type template-parameter shall have one of the following
261 // (optionally cv-qualified) types:
262 //
263 // -- integral or enumeration type,
264 if (T->isIntegralType() || T->isEnumeralType() ||
265 // -- pointer to object or pointer to function,
266 (T->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +0000267 (T->getAs<PointerType>()->getPointeeType()->isObjectType() ||
268 T->getAs<PointerType>()->getPointeeType()->isFunctionType())) ||
Douglas Gregor2943aed2009-03-03 04:44:36 +0000269 // -- reference to object or reference to function,
270 T->isReferenceType() ||
271 // -- pointer to member.
272 T->isMemberPointerType() ||
273 // If T is a dependent type, we can't do the check now, so we
274 // assume that it is well-formed.
275 T->isDependentType())
276 return T;
277 // C++ [temp.param]p8:
278 //
279 // A non-type template-parameter of type "array of T" or
280 // "function returning T" is adjusted to be of type "pointer to
281 // T" or "pointer to function returning T", respectively.
282 else if (T->isArrayType())
283 // FIXME: Keep the type prior to promotion?
284 return Context.getArrayDecayedType(T);
285 else if (T->isFunctionType())
286 // FIXME: Keep the type prior to promotion?
287 return Context.getPointerType(T);
288
289 Diag(Loc, diag::err_template_nontype_parm_bad_type)
290 << T;
291
292 return QualType();
293}
294
Douglas Gregor72c3f312008-12-05 18:15:24 +0000295/// ActOnNonTypeTemplateParameter - Called when a C++ non-type
296/// template parameter (e.g., "int Size" in "template<int Size>
297/// class Array") has been parsed. S is the current scope and D is
298/// the parsed declarator.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000299Sema::DeclPtrTy Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
300 unsigned Depth,
301 unsigned Position) {
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000302 DeclaratorInfo *DInfo = 0;
303 QualType T = GetTypeForDeclarator(D, S, &DInfo);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000304
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000305 assert(S->isTemplateParamScope() &&
306 "Non-type template parameter not in template parameter scope!");
Douglas Gregor72c3f312008-12-05 18:15:24 +0000307 bool Invalid = false;
308
309 IdentifierInfo *ParamName = D.getIdentifier();
310 if (ParamName) {
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000311 NamedDecl *PrevDecl = LookupName(S, ParamName, LookupTagName);
Douglas Gregorf57172b2008-12-08 18:40:42 +0000312 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor72c3f312008-12-05 18:15:24 +0000313 Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000314 PrevDecl);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000315 }
316
Douglas Gregor2943aed2009-03-03 04:44:36 +0000317 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
Douglas Gregorceef30c2009-03-09 16:46:39 +0000318 if (T.isNull()) {
Douglas Gregor2943aed2009-03-03 04:44:36 +0000319 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregorceef30c2009-03-09 16:46:39 +0000320 Invalid = true;
321 }
Douglas Gregor5d290d52009-02-10 17:43:50 +0000322
Douglas Gregor72c3f312008-12-05 18:15:24 +0000323 NonTypeTemplateParmDecl *Param
324 = NonTypeTemplateParmDecl::Create(Context, CurContext, D.getIdentifierLoc(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000325 Depth, Position, ParamName, T, DInfo);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000326 if (Invalid)
327 Param->setInvalidDecl();
328
329 if (D.getIdentifier()) {
330 // Add the template parameter into the current scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000331 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor72c3f312008-12-05 18:15:24 +0000332 IdResolver.AddDecl(Param);
333 }
Chris Lattnerb28317a2009-03-28 19:18:32 +0000334 return DeclPtrTy::make(Param);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000335}
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000336
Douglas Gregord684b002009-02-10 19:49:53 +0000337/// \brief Adds a default argument to the given non-type template
338/// parameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000339void Sema::ActOnNonTypeTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregord684b002009-02-10 19:49:53 +0000340 SourceLocation EqualLoc,
341 ExprArg DefaultE) {
342 NonTypeTemplateParmDecl *TemplateParm
Chris Lattnerb28317a2009-03-28 19:18:32 +0000343 = cast<NonTypeTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregord684b002009-02-10 19:49:53 +0000344 Expr *Default = static_cast<Expr *>(DefaultE.get());
345
346 // C++ [temp.param]p14:
347 // A template-parameter shall not be used in its own default argument.
348 // FIXME: Implement this check! Needs a recursive walk over the types.
349
350 // Check the well-formedness of the default template argument.
Douglas Gregor02cbbd22009-06-11 18:10:32 +0000351 TemplateArgument Converted;
352 if (CheckTemplateArgument(TemplateParm, TemplateParm->getType(), Default,
353 Converted)) {
Douglas Gregord684b002009-02-10 19:49:53 +0000354 TemplateParm->setInvalidDecl();
355 return;
356 }
357
Anders Carlssone9146f22009-05-01 19:49:17 +0000358 TemplateParm->setDefaultArgument(DefaultE.takeAs<Expr>());
Douglas Gregord684b002009-02-10 19:49:53 +0000359}
360
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000361
362/// ActOnTemplateTemplateParameter - Called when a C++ template template
363/// parameter (e.g. T in template <template <typename> class T> class array)
364/// has been parsed. S is the current scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000365Sema::DeclPtrTy Sema::ActOnTemplateTemplateParameter(Scope* S,
366 SourceLocation TmpLoc,
367 TemplateParamsTy *Params,
368 IdentifierInfo *Name,
369 SourceLocation NameLoc,
370 unsigned Depth,
371 unsigned Position)
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000372{
373 assert(S->isTemplateParamScope() &&
374 "Template template parameter not in template parameter scope!");
375
376 // Construct the parameter object.
377 TemplateTemplateParmDecl *Param =
378 TemplateTemplateParmDecl::Create(Context, CurContext, TmpLoc, Depth,
379 Position, Name,
380 (TemplateParameterList*)Params);
381
382 // Make sure the parameter is valid.
383 // FIXME: Decl object is not currently invalidated anywhere so this doesn't
384 // do anything yet. However, if the template parameter list or (eventual)
385 // default value is ever invalidated, that will propagate here.
386 bool Invalid = false;
387 if (Invalid) {
388 Param->setInvalidDecl();
389 }
390
391 // If the tt-param has a name, then link the identifier into the scope
392 // and lookup mechanisms.
393 if (Name) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000394 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000395 IdResolver.AddDecl(Param);
396 }
397
Chris Lattnerb28317a2009-03-28 19:18:32 +0000398 return DeclPtrTy::make(Param);
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000399}
400
Douglas Gregord684b002009-02-10 19:49:53 +0000401/// \brief Adds a default argument to the given template template
402/// parameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000403void Sema::ActOnTemplateTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregord684b002009-02-10 19:49:53 +0000404 SourceLocation EqualLoc,
405 ExprArg DefaultE) {
406 TemplateTemplateParmDecl *TemplateParm
Chris Lattnerb28317a2009-03-28 19:18:32 +0000407 = cast<TemplateTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregord684b002009-02-10 19:49:53 +0000408
409 // Since a template-template parameter's default argument is an
410 // id-expression, it must be a DeclRefExpr.
411 DeclRefExpr *Default
412 = cast<DeclRefExpr>(static_cast<Expr *>(DefaultE.get()));
413
414 // C++ [temp.param]p14:
415 // A template-parameter shall not be used in its own default argument.
416 // FIXME: Implement this check! Needs a recursive walk over the types.
417
418 // Check the well-formedness of the template argument.
419 if (!isa<TemplateDecl>(Default->getDecl())) {
420 Diag(Default->getSourceRange().getBegin(),
421 diag::err_template_arg_must_be_template)
422 << Default->getSourceRange();
423 TemplateParm->setInvalidDecl();
424 return;
425 }
426 if (CheckTemplateArgument(TemplateParm, Default)) {
427 TemplateParm->setInvalidDecl();
428 return;
429 }
430
431 DefaultE.release();
432 TemplateParm->setDefaultArgument(Default);
433}
434
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000435/// ActOnTemplateParameterList - Builds a TemplateParameterList that
436/// contains the template parameters in Params/NumParams.
437Sema::TemplateParamsTy *
438Sema::ActOnTemplateParameterList(unsigned Depth,
439 SourceLocation ExportLoc,
440 SourceLocation TemplateLoc,
441 SourceLocation LAngleLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +0000442 DeclPtrTy *Params, unsigned NumParams,
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000443 SourceLocation RAngleLoc) {
444 if (ExportLoc.isValid())
445 Diag(ExportLoc, diag::note_template_export_unsupported);
446
Douglas Gregorddc29e12009-02-06 22:42:48 +0000447 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
448 (Decl**)Params, NumParams, RAngleLoc);
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000449}
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000450
Douglas Gregor212e81c2009-03-25 00:13:59 +0000451Sema::DeclResult
John McCall0f434ec2009-07-31 02:45:11 +0000452Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
Douglas Gregorddc29e12009-02-06 22:42:48 +0000453 SourceLocation KWLoc, const CXXScopeSpec &SS,
454 IdentifierInfo *Name, SourceLocation NameLoc,
455 AttributeList *Attr,
Douglas Gregor05396e22009-08-25 17:23:04 +0000456 TemplateParameterList *TemplateParams,
Anders Carlsson5aeccdb2009-03-26 00:52:18 +0000457 AccessSpecifier AS) {
Douglas Gregor05396e22009-08-25 17:23:04 +0000458 assert(TemplateParams && TemplateParams->size() > 0 &&
459 "No template parameters");
John McCall0f434ec2009-07-31 02:45:11 +0000460 assert(TUK != TUK_Reference && "Can only declare or define class templates");
Douglas Gregord684b002009-02-10 19:49:53 +0000461 bool Invalid = false;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000462
463 // Check that we can declare a template here.
Douglas Gregor05396e22009-08-25 17:23:04 +0000464 if (CheckTemplateDeclScope(S, TemplateParams))
Douglas Gregor212e81c2009-03-25 00:13:59 +0000465 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000466
467 TagDecl::TagKind Kind;
468 switch (TagSpec) {
469 default: assert(0 && "Unknown tag type!");
470 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
471 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
472 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
473 }
474
475 // There is no such thing as an unnamed class template.
476 if (!Name) {
477 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregor212e81c2009-03-25 00:13:59 +0000478 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000479 }
480
481 // Find any previous declaration with this name.
Douglas Gregor05396e22009-08-25 17:23:04 +0000482 DeclContext *SemanticContext;
483 LookupResult Previous;
484 if (SS.isNotEmpty() && !SS.isInvalid()) {
485 SemanticContext = computeDeclContext(SS, true);
486 if (!SemanticContext) {
487 // FIXME: Produce a reasonable diagnostic here
488 return true;
489 }
490
491 Previous = LookupQualifiedName(SemanticContext, Name, LookupOrdinaryName,
492 true);
493 } else {
494 SemanticContext = CurContext;
495 Previous = LookupName(S, Name, LookupOrdinaryName, true);
496 }
497
Douglas Gregorddc29e12009-02-06 22:42:48 +0000498 assert(!Previous.isAmbiguous() && "Ambiguity in class template redecl?");
499 NamedDecl *PrevDecl = 0;
500 if (Previous.begin() != Previous.end())
501 PrevDecl = *Previous.begin();
502
Douglas Gregor05396e22009-08-25 17:23:04 +0000503 if (PrevDecl && !isDeclInScope(PrevDecl, SemanticContext, S))
Douglas Gregorc19ee3e2009-06-17 23:37:01 +0000504 PrevDecl = 0;
505
Douglas Gregorddc29e12009-02-06 22:42:48 +0000506 // If there is a previous declaration with the same name, check
507 // whether this is a valid redeclaration.
508 ClassTemplateDecl *PrevClassTemplate
509 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
510 if (PrevClassTemplate) {
511 // Ensure that the template parameter lists are compatible.
512 if (!TemplateParameterListsAreEqual(TemplateParams,
513 PrevClassTemplate->getTemplateParameters(),
514 /*Complain=*/true))
Douglas Gregor212e81c2009-03-25 00:13:59 +0000515 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000516
517 // C++ [temp.class]p4:
518 // In a redeclaration, partial specialization, explicit
519 // specialization or explicit instantiation of a class template,
520 // the class-key shall agree in kind with the original class
521 // template declaration (7.1.5.3).
522 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Douglas Gregor501c5ce2009-05-14 16:41:31 +0000523 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind, KWLoc, *Name)) {
Douglas Gregora3a83512009-04-01 23:51:29 +0000524 Diag(KWLoc, diag::err_use_with_wrong_tag)
525 << Name
526 << CodeModificationHint::CreateReplacement(KWLoc,
527 PrevRecordDecl->getKindName());
Douglas Gregorddc29e12009-02-06 22:42:48 +0000528 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregora3a83512009-04-01 23:51:29 +0000529 Kind = PrevRecordDecl->getTagKind();
Douglas Gregorddc29e12009-02-06 22:42:48 +0000530 }
531
Douglas Gregorddc29e12009-02-06 22:42:48 +0000532 // Check for redefinition of this class template.
John McCall0f434ec2009-07-31 02:45:11 +0000533 if (TUK == TUK_Definition) {
Douglas Gregorddc29e12009-02-06 22:42:48 +0000534 if (TagDecl *Def = PrevRecordDecl->getDefinition(Context)) {
535 Diag(NameLoc, diag::err_redefinition) << Name;
536 Diag(Def->getLocation(), diag::note_previous_definition);
537 // FIXME: Would it make sense to try to "forget" the previous
538 // definition, as part of error recovery?
Douglas Gregor212e81c2009-03-25 00:13:59 +0000539 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000540 }
541 }
542 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
543 // Maybe we will complain about the shadowed template parameter.
544 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
545 // Just pretend that we didn't see the previous declaration.
546 PrevDecl = 0;
547 } else if (PrevDecl) {
548 // C++ [temp]p5:
549 // A class template shall not have the same name as any other
550 // template, class, function, object, enumeration, enumerator,
551 // namespace, or type in the same scope (3.3), except as specified
552 // in (14.5.4).
553 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
554 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor212e81c2009-03-25 00:13:59 +0000555 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000556 }
557
Douglas Gregord684b002009-02-10 19:49:53 +0000558 // Check the template parameter list of this declaration, possibly
559 // merging in the template parameter list from the previous class
560 // template declaration.
561 if (CheckTemplateParameterList(TemplateParams,
562 PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0))
563 Invalid = true;
564
Douglas Gregor7da97d02009-05-10 22:57:19 +0000565 // FIXME: If we had a scope specifier, we better have a previous template
Douglas Gregorddc29e12009-02-06 22:42:48 +0000566 // declaration!
567
Douglas Gregorbefc20e2009-03-26 00:10:35 +0000568 CXXRecordDecl *NewClass =
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000569 CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name, KWLoc,
Douglas Gregorddc29e12009-02-06 22:42:48 +0000570 PrevClassTemplate?
Douglas Gregoraafc0cc2009-05-15 19:11:46 +0000571 PrevClassTemplate->getTemplatedDecl() : 0,
572 /*DelayTypeCreation=*/true);
Douglas Gregorddc29e12009-02-06 22:42:48 +0000573
574 ClassTemplateDecl *NewTemplate
575 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
576 DeclarationName(Name), TemplateParams,
Douglas Gregor5953d8b2009-03-19 17:26:29 +0000577 NewClass, PrevClassTemplate);
Douglas Gregorbefc20e2009-03-26 00:10:35 +0000578 NewClass->setDescribedClassTemplate(NewTemplate);
579
Douglas Gregoraafc0cc2009-05-15 19:11:46 +0000580 // Build the type for the class template declaration now.
581 QualType T =
582 Context.getTypeDeclType(NewClass,
583 PrevClassTemplate?
584 PrevClassTemplate->getTemplatedDecl() : 0);
585 assert(T->isDependentType() && "Class template type is not dependent?");
586 (void)T;
587
Anders Carlsson4cbe82c2009-03-26 01:24:28 +0000588 // Set the access specifier.
589 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
590
Douglas Gregorddc29e12009-02-06 22:42:48 +0000591 // Set the lexical context of these templates
592 NewClass->setLexicalDeclContext(CurContext);
593 NewTemplate->setLexicalDeclContext(CurContext);
594
John McCall0f434ec2009-07-31 02:45:11 +0000595 if (TUK == TUK_Definition)
Douglas Gregorddc29e12009-02-06 22:42:48 +0000596 NewClass->startDefinition();
597
598 if (Attr)
Douglas Gregor9cdda0c2009-06-17 21:51:59 +0000599 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregorddc29e12009-02-06 22:42:48 +0000600
601 PushOnScopeChains(NewTemplate, S);
602
Douglas Gregord684b002009-02-10 19:49:53 +0000603 if (Invalid) {
604 NewTemplate->setInvalidDecl();
605 NewClass->setInvalidDecl();
606 }
Chris Lattnerb28317a2009-03-28 19:18:32 +0000607 return DeclPtrTy::make(NewTemplate);
Douglas Gregorddc29e12009-02-06 22:42:48 +0000608}
609
Douglas Gregord684b002009-02-10 19:49:53 +0000610/// \brief Checks the validity of a template parameter list, possibly
611/// considering the template parameter list from a previous
612/// declaration.
613///
614/// If an "old" template parameter list is provided, it must be
615/// equivalent (per TemplateParameterListsAreEqual) to the "new"
616/// template parameter list.
617///
618/// \param NewParams Template parameter list for a new template
619/// declaration. This template parameter list will be updated with any
620/// default arguments that are carried through from the previous
621/// template parameter list.
622///
623/// \param OldParams If provided, template parameter list from a
624/// previous declaration of the same template. Default template
625/// arguments will be merged from the old template parameter list to
626/// the new template parameter list.
627///
628/// \returns true if an error occurred, false otherwise.
629bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
630 TemplateParameterList *OldParams) {
631 bool Invalid = false;
632
633 // C++ [temp.param]p10:
634 // The set of default template-arguments available for use with a
635 // template declaration or definition is obtained by merging the
636 // default arguments from the definition (if in scope) and all
637 // declarations in scope in the same way default function
638 // arguments are (8.3.6).
639 bool SawDefaultArgument = false;
640 SourceLocation PreviousDefaultArgLoc;
Douglas Gregorc15cb382009-02-09 23:23:08 +0000641
Anders Carlsson49d25572009-06-12 23:20:15 +0000642 bool SawParameterPack = false;
643 SourceLocation ParameterPackLoc;
644
Mike Stump1a35fde2009-02-11 23:03:27 +0000645 // Dummy initialization to avoid warnings.
Douglas Gregor1bc69132009-02-11 20:46:19 +0000646 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregord684b002009-02-10 19:49:53 +0000647 if (OldParams)
648 OldParam = OldParams->begin();
649
650 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
651 NewParamEnd = NewParams->end();
652 NewParam != NewParamEnd; ++NewParam) {
653 // Variables used to diagnose redundant default arguments
654 bool RedundantDefaultArg = false;
655 SourceLocation OldDefaultLoc;
656 SourceLocation NewDefaultLoc;
657
658 // Variables used to diagnose missing default arguments
659 bool MissingDefaultArg = false;
660
Anders Carlsson49d25572009-06-12 23:20:15 +0000661 // C++0x [temp.param]p11:
662 // If a template parameter of a class template is a template parameter pack,
663 // it must be the last template parameter.
664 if (SawParameterPack) {
665 Diag(ParameterPackLoc,
666 diag::err_template_param_pack_must_be_last_template_parameter);
667 Invalid = true;
668 }
669
Douglas Gregord684b002009-02-10 19:49:53 +0000670 // Merge default arguments for template type parameters.
671 if (TemplateTypeParmDecl *NewTypeParm
672 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
673 TemplateTypeParmDecl *OldTypeParm
674 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
675
Anders Carlsson49d25572009-06-12 23:20:15 +0000676 if (NewTypeParm->isParameterPack()) {
677 assert(!NewTypeParm->hasDefaultArgument() &&
678 "Parameter packs can't have a default argument!");
679 SawParameterPack = true;
680 ParameterPackLoc = NewTypeParm->getLocation();
681 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
Douglas Gregord684b002009-02-10 19:49:53 +0000682 NewTypeParm->hasDefaultArgument()) {
683 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
684 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
685 SawDefaultArgument = true;
686 RedundantDefaultArg = true;
687 PreviousDefaultArgLoc = NewDefaultLoc;
688 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
689 // Merge the default argument from the old declaration to the
690 // new declaration.
691 SawDefaultArgument = true;
692 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgument(),
693 OldTypeParm->getDefaultArgumentLoc(),
694 true);
695 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
696 } else if (NewTypeParm->hasDefaultArgument()) {
697 SawDefaultArgument = true;
698 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
699 } else if (SawDefaultArgument)
700 MissingDefaultArg = true;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000701 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
Douglas Gregord684b002009-02-10 19:49:53 +0000702 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000703 // Merge default arguments for non-type template parameters
Douglas Gregord684b002009-02-10 19:49:53 +0000704 NonTypeTemplateParmDecl *OldNonTypeParm
705 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
706 if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
707 NewNonTypeParm->hasDefaultArgument()) {
708 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
709 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
710 SawDefaultArgument = true;
711 RedundantDefaultArg = true;
712 PreviousDefaultArgLoc = NewDefaultLoc;
713 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
714 // Merge the default argument from the old declaration to the
715 // new declaration.
716 SawDefaultArgument = true;
717 // FIXME: We need to create a new kind of "default argument"
718 // expression that points to a previous template template
719 // parameter.
720 NewNonTypeParm->setDefaultArgument(
721 OldNonTypeParm->getDefaultArgument());
722 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
723 } else if (NewNonTypeParm->hasDefaultArgument()) {
724 SawDefaultArgument = true;
725 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
726 } else if (SawDefaultArgument)
727 MissingDefaultArg = true;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000728 } else {
Douglas Gregord684b002009-02-10 19:49:53 +0000729 // Merge default arguments for template template parameters
Douglas Gregord684b002009-02-10 19:49:53 +0000730 TemplateTemplateParmDecl *NewTemplateParm
731 = cast<TemplateTemplateParmDecl>(*NewParam);
732 TemplateTemplateParmDecl *OldTemplateParm
733 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
734 if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
735 NewTemplateParm->hasDefaultArgument()) {
736 OldDefaultLoc = OldTemplateParm->getDefaultArgumentLoc();
737 NewDefaultLoc = NewTemplateParm->getDefaultArgumentLoc();
738 SawDefaultArgument = true;
739 RedundantDefaultArg = true;
740 PreviousDefaultArgLoc = NewDefaultLoc;
741 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
742 // Merge the default argument from the old declaration to the
743 // new declaration.
744 SawDefaultArgument = true;
Mike Stump390b4cc2009-05-16 07:39:55 +0000745 // FIXME: We need to create a new kind of "default argument" expression
746 // that points to a previous template template parameter.
Douglas Gregord684b002009-02-10 19:49:53 +0000747 NewTemplateParm->setDefaultArgument(
748 OldTemplateParm->getDefaultArgument());
749 PreviousDefaultArgLoc = OldTemplateParm->getDefaultArgumentLoc();
750 } else if (NewTemplateParm->hasDefaultArgument()) {
751 SawDefaultArgument = true;
752 PreviousDefaultArgLoc = NewTemplateParm->getDefaultArgumentLoc();
753 } else if (SawDefaultArgument)
754 MissingDefaultArg = true;
755 }
756
757 if (RedundantDefaultArg) {
758 // C++ [temp.param]p12:
759 // A template-parameter shall not be given default arguments
760 // by two different declarations in the same scope.
761 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
762 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
763 Invalid = true;
764 } else if (MissingDefaultArg) {
765 // C++ [temp.param]p11:
766 // If a template-parameter has a default template-argument,
767 // all subsequent template-parameters shall have a default
768 // template-argument supplied.
769 Diag((*NewParam)->getLocation(),
770 diag::err_template_param_default_arg_missing);
771 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
772 Invalid = true;
773 }
774
775 // If we have an old template parameter list that we're merging
776 // in, move on to the next parameter.
777 if (OldParams)
778 ++OldParam;
779 }
780
781 return Invalid;
782}
Douglas Gregorc15cb382009-02-09 23:23:08 +0000783
Douglas Gregorf59a56e2009-07-21 23:53:31 +0000784/// \brief Match the given template parameter lists to the given scope
785/// specifier, returning the template parameter list that applies to the
786/// name.
787///
788/// \param DeclStartLoc the start of the declaration that has a scope
789/// specifier or a template parameter list.
790///
791/// \param SS the scope specifier that will be matched to the given template
792/// parameter lists. This scope specifier precedes a qualified name that is
793/// being declared.
794///
795/// \param ParamLists the template parameter lists, from the outermost to the
796/// innermost template parameter lists.
797///
798/// \param NumParamLists the number of template parameter lists in ParamLists.
799///
800/// \returns the template parameter list, if any, that corresponds to the
801/// name that is preceded by the scope specifier @p SS. This template
802/// parameter list may be have template parameters (if we're declaring a
803/// template) or may have no template parameters (if we're declaring a
804/// template specialization), or may be NULL (if we were's declaring isn't
805/// itself a template).
806TemplateParameterList *
807Sema::MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc,
808 const CXXScopeSpec &SS,
809 TemplateParameterList **ParamLists,
810 unsigned NumParamLists) {
811 // FIXME: This routine will need a lot more testing once we have support for
812 // member templates.
813
814 // Find the template-ids that occur within the nested-name-specifier. These
815 // template-ids will match up with the template parameter lists.
816 llvm::SmallVector<const TemplateSpecializationType *, 4>
817 TemplateIdsInSpecifier;
818 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
819 NNS; NNS = NNS->getPrefix()) {
820 if (const TemplateSpecializationType *SpecType
821 = dyn_cast_or_null<TemplateSpecializationType>(NNS->getAsType())) {
822 TemplateDecl *Template = SpecType->getTemplateName().getAsTemplateDecl();
823 if (!Template)
824 continue; // FIXME: should this be an error? probably...
825
Ted Kremenek6217b802009-07-29 21:53:49 +0000826 if (const RecordType *Record = SpecType->getAs<RecordType>()) {
Douglas Gregorf59a56e2009-07-21 23:53:31 +0000827 ClassTemplateSpecializationDecl *SpecDecl
828 = cast<ClassTemplateSpecializationDecl>(Record->getDecl());
829 // If the nested name specifier refers to an explicit specialization,
830 // we don't need a template<> header.
Douglas Gregorb88e8882009-07-30 17:40:51 +0000831 // FIXME: revisit this approach once we cope with specialization
832 // properly.
Douglas Gregorf59a56e2009-07-21 23:53:31 +0000833 if (SpecDecl->getSpecializationKind() == TSK_ExplicitSpecialization)
834 continue;
835 }
836
837 TemplateIdsInSpecifier.push_back(SpecType);
838 }
839 }
840
841 // Reverse the list of template-ids in the scope specifier, so that we can
842 // more easily match up the template-ids and the template parameter lists.
843 std::reverse(TemplateIdsInSpecifier.begin(), TemplateIdsInSpecifier.end());
844
845 SourceLocation FirstTemplateLoc = DeclStartLoc;
846 if (NumParamLists)
847 FirstTemplateLoc = ParamLists[0]->getTemplateLoc();
848
849 // Match the template-ids found in the specifier to the template parameter
850 // lists.
851 unsigned Idx = 0;
852 for (unsigned NumTemplateIds = TemplateIdsInSpecifier.size();
853 Idx != NumTemplateIds; ++Idx) {
Douglas Gregorb88e8882009-07-30 17:40:51 +0000854 QualType TemplateId = QualType(TemplateIdsInSpecifier[Idx], 0);
855 bool DependentTemplateId = TemplateId->isDependentType();
Douglas Gregorf59a56e2009-07-21 23:53:31 +0000856 if (Idx >= NumParamLists) {
857 // We have a template-id without a corresponding template parameter
858 // list.
859 if (DependentTemplateId) {
860 // FIXME: the location information here isn't great.
861 Diag(SS.getRange().getBegin(),
862 diag::err_template_spec_needs_template_parameters)
Douglas Gregorb88e8882009-07-30 17:40:51 +0000863 << TemplateId
Douglas Gregorf59a56e2009-07-21 23:53:31 +0000864 << SS.getRange();
865 } else {
866 Diag(SS.getRange().getBegin(), diag::err_template_spec_needs_header)
867 << SS.getRange()
868 << CodeModificationHint::CreateInsertion(FirstTemplateLoc,
869 "template<> ");
870 }
871 return 0;
872 }
873
874 // Check the template parameter list against its corresponding template-id.
Douglas Gregorb88e8882009-07-30 17:40:51 +0000875 if (DependentTemplateId) {
876 TemplateDecl *Template
877 = TemplateIdsInSpecifier[Idx]->getTemplateName().getAsTemplateDecl();
878
879 if (ClassTemplateDecl *ClassTemplate
880 = dyn_cast<ClassTemplateDecl>(Template)) {
881 TemplateParameterList *ExpectedTemplateParams = 0;
882 // Is this template-id naming the primary template?
883 if (Context.hasSameType(TemplateId,
884 ClassTemplate->getInjectedClassNameType(Context)))
885 ExpectedTemplateParams = ClassTemplate->getTemplateParameters();
886 // ... or a partial specialization?
887 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
888 = ClassTemplate->findPartialSpecialization(TemplateId))
889 ExpectedTemplateParams = PartialSpec->getTemplateParameters();
890
891 if (ExpectedTemplateParams)
892 TemplateParameterListsAreEqual(ParamLists[Idx],
893 ExpectedTemplateParams,
894 true);
895 }
896 } else if (ParamLists[Idx]->size() > 0)
897 Diag(ParamLists[Idx]->getTemplateLoc(),
898 diag::err_template_param_list_matches_nontemplate)
899 << TemplateId
900 << ParamLists[Idx]->getSourceRange();
Douglas Gregorf59a56e2009-07-21 23:53:31 +0000901 }
902
903 // If there were at least as many template-ids as there were template
904 // parameter lists, then there are no template parameter lists remaining for
905 // the declaration itself.
906 if (Idx >= NumParamLists)
907 return 0;
908
909 // If there were too many template parameter lists, complain about that now.
910 if (Idx != NumParamLists - 1) {
911 while (Idx < NumParamLists - 1) {
912 Diag(ParamLists[Idx]->getTemplateLoc(),
913 diag::err_template_spec_extra_headers)
914 << SourceRange(ParamLists[Idx]->getTemplateLoc(),
915 ParamLists[Idx]->getRAngleLoc());
916 ++Idx;
917 }
918 }
919
920 // Return the last template parameter list, which corresponds to the
921 // entity being declared.
922 return ParamLists[NumParamLists - 1];
923}
924
Douglas Gregor40808ce2009-03-09 23:48:35 +0000925/// \brief Translates template arguments as provided by the parser
926/// into template arguments used by semantic analysis.
927static void
928translateTemplateArguments(ASTTemplateArgsPtr &TemplateArgsIn,
929 SourceLocation *TemplateArgLocs,
930 llvm::SmallVector<TemplateArgument, 16> &TemplateArgs) {
931 TemplateArgs.reserve(TemplateArgsIn.size());
932
933 void **Args = TemplateArgsIn.getArgs();
934 bool *ArgIsType = TemplateArgsIn.getArgIsType();
935 for (unsigned Arg = 0, Last = TemplateArgsIn.size(); Arg != Last; ++Arg) {
936 TemplateArgs.push_back(
937 ArgIsType[Arg]? TemplateArgument(TemplateArgLocs[Arg],
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000938 //FIXME: Preserve type source info.
939 Sema::GetTypeFromParser(Args[Arg]))
Douglas Gregor40808ce2009-03-09 23:48:35 +0000940 : TemplateArgument(reinterpret_cast<Expr *>(Args[Arg])));
941 }
942}
943
Douglas Gregor7532dc62009-03-30 22:58:21 +0000944QualType Sema::CheckTemplateIdType(TemplateName Name,
945 SourceLocation TemplateLoc,
946 SourceLocation LAngleLoc,
947 const TemplateArgument *TemplateArgs,
948 unsigned NumTemplateArgs,
949 SourceLocation RAngleLoc) {
950 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregorc45c2322009-03-31 00:43:58 +0000951 if (!Template) {
952 // The template name does not resolve to a template, so we just
953 // build a dependent template-id type.
Douglas Gregorc45c2322009-03-31 00:43:58 +0000954 return Context.getTemplateSpecializationType(Name, TemplateArgs,
Douglas Gregor1275ae02009-07-28 23:00:59 +0000955 NumTemplateArgs);
Douglas Gregorc45c2322009-03-31 00:43:58 +0000956 }
Douglas Gregor7532dc62009-03-30 22:58:21 +0000957
Douglas Gregor40808ce2009-03-09 23:48:35 +0000958 // Check that the template argument list is well-formed for this
959 // template.
Anders Carlssonfb250522009-06-23 01:26:57 +0000960 TemplateArgumentListBuilder Converted(Template->getTemplateParameters(),
961 NumTemplateArgs);
Douglas Gregor7532dc62009-03-30 22:58:21 +0000962 if (CheckTemplateArgumentList(Template, TemplateLoc, LAngleLoc,
Douglas Gregor40808ce2009-03-09 23:48:35 +0000963 TemplateArgs, NumTemplateArgs, RAngleLoc,
Douglas Gregor16134c62009-07-01 00:28:38 +0000964 false, Converted))
Douglas Gregor40808ce2009-03-09 23:48:35 +0000965 return QualType();
966
Anders Carlssonfb250522009-06-23 01:26:57 +0000967 assert((Converted.structuredSize() ==
Douglas Gregor7532dc62009-03-30 22:58:21 +0000968 Template->getTemplateParameters()->size()) &&
Douglas Gregor40808ce2009-03-09 23:48:35 +0000969 "Converted template argument list is too short!");
970
971 QualType CanonType;
972
Douglas Gregor7532dc62009-03-30 22:58:21 +0000973 if (TemplateSpecializationType::anyDependentTemplateArguments(
Douglas Gregor40808ce2009-03-09 23:48:35 +0000974 TemplateArgs,
975 NumTemplateArgs)) {
976 // This class template specialization is a dependent
977 // type. Therefore, its canonical type is another class template
978 // specialization type that contains all of the converted
979 // arguments in canonical form. This ensures that, e.g., A<T> and
980 // A<T, T> have identical types when A is declared as:
981 //
982 // template<typename T, typename U = T> struct A;
Douglas Gregor25a3ef72009-05-07 06:41:52 +0000983 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
984 CanonType = Context.getTemplateSpecializationType(CanonName,
Anders Carlssonfb250522009-06-23 01:26:57 +0000985 Converted.getFlatArguments(),
986 Converted.flatSize());
Douglas Gregor1275ae02009-07-28 23:00:59 +0000987
988 // FIXME: CanonType is not actually the canonical type, and unfortunately
989 // it is a TemplateTypeSpecializationType that we will never use again.
990 // In the future, we need to teach getTemplateSpecializationType to only
991 // build the canonical type and return that to us.
992 CanonType = Context.getCanonicalType(CanonType);
Douglas Gregor7532dc62009-03-30 22:58:21 +0000993 } else if (ClassTemplateDecl *ClassTemplate
994 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregor40808ce2009-03-09 23:48:35 +0000995 // Find the class template specialization declaration that
996 // corresponds to these arguments.
997 llvm::FoldingSetNodeID ID;
Anders Carlsson1c5976e2009-06-05 03:43:12 +0000998 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlssonfb250522009-06-23 01:26:57 +0000999 Converted.getFlatArguments(),
Douglas Gregor828e2262009-07-29 16:09:57 +00001000 Converted.flatSize(),
1001 Context);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001002 void *InsertPos = 0;
1003 ClassTemplateSpecializationDecl *Decl
1004 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
1005 if (!Decl) {
1006 // This is the first time we have referenced this class template
1007 // specialization. Create the canonical declaration and add it to
1008 // the set of specializations.
1009 Decl = ClassTemplateSpecializationDecl::Create(Context,
Anders Carlsson1c5976e2009-06-05 03:43:12 +00001010 ClassTemplate->getDeclContext(),
1011 TemplateLoc,
1012 ClassTemplate,
Anders Carlssonfb250522009-06-23 01:26:57 +00001013 Converted, 0);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001014 ClassTemplate->getSpecializations().InsertNode(Decl, InsertPos);
1015 Decl->setLexicalDeclContext(CurContext);
1016 }
1017
1018 CanonType = Context.getTypeDeclType(Decl);
1019 }
1020
1021 // Build the fully-sugared type for this class template
1022 // specialization, which refers back to the class template
1023 // specialization we created or found.
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00001024 //FIXME: Preserve type source info.
Douglas Gregor7532dc62009-03-30 22:58:21 +00001025 return Context.getTemplateSpecializationType(Name, TemplateArgs,
1026 NumTemplateArgs, CanonType);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001027}
1028
Douglas Gregorcc636682009-02-17 23:15:12 +00001029Action::TypeResult
Douglas Gregor7532dc62009-03-30 22:58:21 +00001030Sema::ActOnTemplateIdType(TemplateTy TemplateD, SourceLocation TemplateLoc,
1031 SourceLocation LAngleLoc,
1032 ASTTemplateArgsPtr TemplateArgsIn,
1033 SourceLocation *TemplateArgLocs,
1034 SourceLocation RAngleLoc) {
1035 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Douglas Gregor55f6b142009-02-09 18:46:07 +00001036
Douglas Gregor40808ce2009-03-09 23:48:35 +00001037 // Translate the parser's template argument list in our AST format.
1038 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
1039 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
Douglas Gregorc15cb382009-02-09 23:23:08 +00001040
Douglas Gregor7532dc62009-03-30 22:58:21 +00001041 QualType Result = CheckTemplateIdType(Template, TemplateLoc, LAngleLoc,
Jay Foadbeaaccd2009-05-21 09:52:38 +00001042 TemplateArgs.data(),
1043 TemplateArgs.size(),
Douglas Gregor7532dc62009-03-30 22:58:21 +00001044 RAngleLoc);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001045 TemplateArgsIn.release();
Douglas Gregor31a19b62009-04-01 21:51:26 +00001046
1047 if (Result.isNull())
1048 return true;
1049
Douglas Gregor5908e9f2009-02-09 19:34:22 +00001050 return Result.getAsOpaquePtr();
Douglas Gregor55f6b142009-02-09 18:46:07 +00001051}
1052
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001053Sema::OwningExprResult Sema::BuildTemplateIdExpr(TemplateName Template,
1054 SourceLocation TemplateNameLoc,
1055 SourceLocation LAngleLoc,
1056 const TemplateArgument *TemplateArgs,
1057 unsigned NumTemplateArgs,
1058 SourceLocation RAngleLoc) {
1059 // FIXME: Can we do any checking at this point? I guess we could check the
1060 // template arguments that we have against the template name, if the template
1061 // name refers to a single template. That's not a terribly common case,
1062 // though.
1063 return Owned(TemplateIdRefExpr::Create(Context,
1064 /*FIXME: New type?*/Context.OverloadTy,
1065 /*FIXME: Necessary?*/0,
1066 /*FIXME: Necessary?*/SourceRange(),
1067 Template, TemplateNameLoc, LAngleLoc,
1068 TemplateArgs,
1069 NumTemplateArgs, RAngleLoc));
1070}
1071
1072Sema::OwningExprResult Sema::ActOnTemplateIdExpr(TemplateTy TemplateD,
1073 SourceLocation TemplateNameLoc,
1074 SourceLocation LAngleLoc,
1075 ASTTemplateArgsPtr TemplateArgsIn,
1076 SourceLocation *TemplateArgLocs,
1077 SourceLocation RAngleLoc) {
1078 TemplateName Template = TemplateD.getAsVal<TemplateName>();
1079
1080 // Translate the parser's template argument list in our AST format.
1081 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
1082 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001083 TemplateArgsIn.release();
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001084
1085 return BuildTemplateIdExpr(Template, TemplateNameLoc, LAngleLoc,
1086 TemplateArgs.data(), TemplateArgs.size(),
1087 RAngleLoc);
1088}
1089
Douglas Gregorc45c2322009-03-31 00:43:58 +00001090/// \brief Form a dependent template name.
1091///
1092/// This action forms a dependent template name given the template
1093/// name and its (presumably dependent) scope specifier. For
1094/// example, given "MetaFun::template apply", the scope specifier \p
1095/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
1096/// of the "template" keyword, and "apply" is the \p Name.
1097Sema::TemplateTy
1098Sema::ActOnDependentTemplateName(SourceLocation TemplateKWLoc,
1099 const IdentifierInfo &Name,
1100 SourceLocation NameLoc,
1101 const CXXScopeSpec &SS) {
1102 if (!SS.isSet() || SS.isInvalid())
1103 return TemplateTy();
1104
1105 NestedNameSpecifier *Qualifier
1106 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
1107
1108 // FIXME: member of the current instantiation
1109
1110 if (!Qualifier->isDependent()) {
1111 // C++0x [temp.names]p5:
1112 // If a name prefixed by the keyword template is not the name of
1113 // a template, the program is ill-formed. [Note: the keyword
1114 // template may not be applied to non-template members of class
1115 // templates. -end note ] [ Note: as is the case with the
1116 // typename prefix, the template prefix is allowed in cases
1117 // where it is not strictly necessary; i.e., when the
1118 // nested-name-specifier or the expression on the left of the ->
1119 // or . is not dependent on a template-parameter, or the use
1120 // does not appear in the scope of a template. -end note]
1121 //
1122 // Note: C++03 was more strict here, because it banned the use of
1123 // the "template" keyword prior to a template-name that was not a
1124 // dependent name. C++ DR468 relaxed this requirement (the
1125 // "template" keyword is now permitted). We follow the C++0x
1126 // rules, even in C++03 mode, retroactively applying the DR.
1127 TemplateTy Template;
Douglas Gregor495c35d2009-08-25 22:51:20 +00001128 TemplateNameKind TNK = isTemplateName(Name, 0, &SS, false, Template);
Douglas Gregorc45c2322009-03-31 00:43:58 +00001129 if (TNK == TNK_Non_template) {
1130 Diag(NameLoc, diag::err_template_kw_refers_to_non_template)
1131 << &Name;
1132 return TemplateTy();
1133 }
1134
1135 return Template;
1136 }
1137
1138 return TemplateTy::make(Context.getDependentTemplateName(Qualifier, &Name));
1139}
1140
Anders Carlsson436b1562009-06-13 00:33:33 +00001141bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
1142 const TemplateArgument &Arg,
1143 TemplateArgumentListBuilder &Converted) {
1144 // Check template type parameter.
1145 if (Arg.getKind() != TemplateArgument::Type) {
1146 // C++ [temp.arg.type]p1:
1147 // A template-argument for a template-parameter which is a
1148 // type shall be a type-id.
1149
1150 // We have a template type parameter but the template argument
1151 // is not a type.
1152 Diag(Arg.getLocation(), diag::err_template_arg_must_be_type);
1153 Diag(Param->getLocation(), diag::note_template_param_here);
1154
1155 return true;
1156 }
1157
1158 if (CheckTemplateArgument(Param, Arg.getAsType(), Arg.getLocation()))
1159 return true;
1160
1161 // Add the converted template type argument.
Anders Carlssonfb250522009-06-23 01:26:57 +00001162 Converted.Append(
Anders Carlsson436b1562009-06-13 00:33:33 +00001163 TemplateArgument(Arg.getLocation(),
1164 Context.getCanonicalType(Arg.getAsType())));
1165 return false;
1166}
1167
Douglas Gregorc15cb382009-02-09 23:23:08 +00001168/// \brief Check that the given template argument list is well-formed
1169/// for specializing the given template.
1170bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
1171 SourceLocation TemplateLoc,
1172 SourceLocation LAngleLoc,
Douglas Gregor40808ce2009-03-09 23:48:35 +00001173 const TemplateArgument *TemplateArgs,
1174 unsigned NumTemplateArgs,
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001175 SourceLocation RAngleLoc,
Douglas Gregor16134c62009-07-01 00:28:38 +00001176 bool PartialTemplateArgs,
Anders Carlsson1c5976e2009-06-05 03:43:12 +00001177 TemplateArgumentListBuilder &Converted) {
Douglas Gregorc15cb382009-02-09 23:23:08 +00001178 TemplateParameterList *Params = Template->getTemplateParameters();
1179 unsigned NumParams = Params->size();
Douglas Gregor40808ce2009-03-09 23:48:35 +00001180 unsigned NumArgs = NumTemplateArgs;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001181 bool Invalid = false;
1182
Anders Carlsson0ceffb52009-06-13 02:08:00 +00001183 bool HasParameterPack =
1184 NumParams > 0 && Params->getParam(NumParams - 1)->isTemplateParameterPack();
1185
1186 if ((NumArgs > NumParams && !HasParameterPack) ||
Douglas Gregor16134c62009-07-01 00:28:38 +00001187 (NumArgs < Params->getMinRequiredArguments() &&
1188 !PartialTemplateArgs)) {
Douglas Gregorc15cb382009-02-09 23:23:08 +00001189 // FIXME: point at either the first arg beyond what we can handle,
1190 // or the '>', depending on whether we have too many or too few
1191 // arguments.
1192 SourceRange Range;
1193 if (NumArgs > NumParams)
Douglas Gregor40808ce2009-03-09 23:48:35 +00001194 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
Douglas Gregorc15cb382009-02-09 23:23:08 +00001195 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
1196 << (NumArgs > NumParams)
1197 << (isa<ClassTemplateDecl>(Template)? 0 :
1198 isa<FunctionTemplateDecl>(Template)? 1 :
1199 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
1200 << Template << Range;
Douglas Gregor62cb18d2009-02-11 18:16:40 +00001201 Diag(Template->getLocation(), diag::note_template_decl_here)
1202 << Params->getSourceRange();
Douglas Gregorc15cb382009-02-09 23:23:08 +00001203 Invalid = true;
1204 }
1205
1206 // C++ [temp.arg]p1:
1207 // [...] The type and form of each template-argument specified in
1208 // a template-id shall match the type and form specified for the
1209 // corresponding parameter declared by the template in its
1210 // template-parameter-list.
1211 unsigned ArgIdx = 0;
1212 for (TemplateParameterList::iterator Param = Params->begin(),
1213 ParamEnd = Params->end();
1214 Param != ParamEnd; ++Param, ++ArgIdx) {
Douglas Gregor16134c62009-07-01 00:28:38 +00001215 if (ArgIdx > NumArgs && PartialTemplateArgs)
1216 break;
1217
Douglas Gregorc15cb382009-02-09 23:23:08 +00001218 // Decode the template argument
Douglas Gregor40808ce2009-03-09 23:48:35 +00001219 TemplateArgument Arg;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001220 if (ArgIdx >= NumArgs) {
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001221 // Retrieve the default template argument from the template
1222 // parameter.
1223 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
Anders Carlsson0ceffb52009-06-13 02:08:00 +00001224 if (TTP->isParameterPack()) {
Anders Carlssonfb250522009-06-23 01:26:57 +00001225 // We have an empty argument pack.
1226 Converted.BeginPack();
1227 Converted.EndPack();
Anders Carlsson0ceffb52009-06-13 02:08:00 +00001228 break;
1229 }
1230
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001231 if (!TTP->hasDefaultArgument())
1232 break;
1233
Douglas Gregor40808ce2009-03-09 23:48:35 +00001234 QualType ArgType = TTP->getDefaultArgument();
Douglas Gregor99ebf652009-02-27 19:31:52 +00001235
1236 // If the argument type is dependent, instantiate it now based
1237 // on the previously-computed template arguments.
Douglas Gregordf667e72009-03-10 20:44:00 +00001238 if (ArgType->isDependentType()) {
1239 InstantiatingTemplate Inst(*this, TemplateLoc,
Anders Carlssonfb250522009-06-23 01:26:57 +00001240 Template, Converted.getFlatArguments(),
Anders Carlsson1c5976e2009-06-05 03:43:12 +00001241 Converted.flatSize(),
Douglas Gregordf667e72009-03-10 20:44:00 +00001242 SourceRange(TemplateLoc, RAngleLoc));
Douglas Gregor7e063902009-05-11 23:53:27 +00001243
Anders Carlssone9c904b2009-06-05 04:47:51 +00001244 TemplateArgumentList TemplateArgs(Context, Converted,
Anders Carlssonfb250522009-06-23 01:26:57 +00001245 /*TakeArgs=*/false);
Douglas Gregord6350ae2009-08-28 20:31:08 +00001246 ArgType = SubstType(ArgType,
1247 MultiLevelTemplateArgumentList(TemplateArgs),
John McCallce3ff2b2009-08-25 22:02:44 +00001248 TTP->getDefaultArgumentLoc(),
1249 TTP->getDeclName());
Douglas Gregordf667e72009-03-10 20:44:00 +00001250 }
Douglas Gregor99ebf652009-02-27 19:31:52 +00001251
1252 if (ArgType.isNull())
Douglas Gregorcd281c32009-02-28 00:25:32 +00001253 return true;
Douglas Gregor99ebf652009-02-27 19:31:52 +00001254
Douglas Gregor40808ce2009-03-09 23:48:35 +00001255 Arg = TemplateArgument(TTP->getLocation(), ArgType);
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001256 } else if (NonTypeTemplateParmDecl *NTTP
1257 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
1258 if (!NTTP->hasDefaultArgument())
1259 break;
1260
Anders Carlsson3b56c002009-06-11 16:06:49 +00001261 InstantiatingTemplate Inst(*this, TemplateLoc,
Anders Carlssonfb250522009-06-23 01:26:57 +00001262 Template, Converted.getFlatArguments(),
Anders Carlsson3b56c002009-06-11 16:06:49 +00001263 Converted.flatSize(),
1264 SourceRange(TemplateLoc, RAngleLoc));
1265
1266 TemplateArgumentList TemplateArgs(Context, Converted,
Anders Carlssonfb250522009-06-23 01:26:57 +00001267 /*TakeArgs=*/false);
Anders Carlsson3b56c002009-06-11 16:06:49 +00001268
Douglas Gregord6350ae2009-08-28 20:31:08 +00001269 Sema::OwningExprResult E
1270 = SubstExpr(NTTP->getDefaultArgument(),
1271 MultiLevelTemplateArgumentList(TemplateArgs));
Anders Carlsson3b56c002009-06-11 16:06:49 +00001272 if (E.isInvalid())
1273 return true;
1274
1275 Arg = TemplateArgument(E.takeAs<Expr>());
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001276 } else {
1277 TemplateTemplateParmDecl *TempParm
1278 = cast<TemplateTemplateParmDecl>(*Param);
1279
1280 if (!TempParm->hasDefaultArgument())
1281 break;
1282
John McCallce3ff2b2009-08-25 22:02:44 +00001283 // FIXME: Subst default argument
Douglas Gregor40808ce2009-03-09 23:48:35 +00001284 Arg = TemplateArgument(TempParm->getDefaultArgument());
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001285 }
1286 } else {
1287 // Retrieve the template argument produced by the user.
Douglas Gregor40808ce2009-03-09 23:48:35 +00001288 Arg = TemplateArgs[ArgIdx];
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001289 }
1290
Douglas Gregorc15cb382009-02-09 23:23:08 +00001291
1292 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
Anders Carlsson0ceffb52009-06-13 02:08:00 +00001293 if (TTP->isParameterPack()) {
Anders Carlssonfb250522009-06-23 01:26:57 +00001294 Converted.BeginPack();
Anders Carlsson0ceffb52009-06-13 02:08:00 +00001295 // Check all the remaining arguments (if any).
1296 for (; ArgIdx < NumArgs; ++ArgIdx) {
1297 if (CheckTemplateTypeArgument(TTP, TemplateArgs[ArgIdx], Converted))
1298 Invalid = true;
1299 }
1300
Anders Carlssonfb250522009-06-23 01:26:57 +00001301 Converted.EndPack();
Anders Carlsson0ceffb52009-06-13 02:08:00 +00001302 } else {
1303 if (CheckTemplateTypeArgument(TTP, Arg, Converted))
1304 Invalid = true;
1305 }
Douglas Gregorc15cb382009-02-09 23:23:08 +00001306 } else if (NonTypeTemplateParmDecl *NTTP
1307 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
1308 // Check non-type template parameters.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001309
John McCallce3ff2b2009-08-25 22:02:44 +00001310 // Do substitution on the type of the non-type template parameter
1311 // with the template arguments we've seen thus far.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001312 QualType NTTPType = NTTP->getType();
1313 if (NTTPType->isDependentType()) {
John McCallce3ff2b2009-08-25 22:02:44 +00001314 // Do substitution on the type of the non-type template parameter.
Douglas Gregordf667e72009-03-10 20:44:00 +00001315 InstantiatingTemplate Inst(*this, TemplateLoc,
Anders Carlssonfb250522009-06-23 01:26:57 +00001316 Template, Converted.getFlatArguments(),
Anders Carlsson1c5976e2009-06-05 03:43:12 +00001317 Converted.flatSize(),
Douglas Gregordf667e72009-03-10 20:44:00 +00001318 SourceRange(TemplateLoc, RAngleLoc));
1319
Anders Carlssone9c904b2009-06-05 04:47:51 +00001320 TemplateArgumentList TemplateArgs(Context, Converted,
Anders Carlssonfb250522009-06-23 01:26:57 +00001321 /*TakeArgs=*/false);
Douglas Gregor357bbd02009-08-28 20:50:45 +00001322 NTTPType = SubstType(NTTPType,
1323 MultiLevelTemplateArgumentList(TemplateArgs),
John McCallce3ff2b2009-08-25 22:02:44 +00001324 NTTP->getLocation(),
1325 NTTP->getDeclName());
Douglas Gregor2943aed2009-03-03 04:44:36 +00001326 // If that worked, check the non-type template parameter type
1327 // for validity.
1328 if (!NTTPType.isNull())
1329 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
1330 NTTP->getLocation());
Douglas Gregor2943aed2009-03-03 04:44:36 +00001331 if (NTTPType.isNull()) {
1332 Invalid = true;
1333 break;
1334 }
1335 }
1336
Douglas Gregor40808ce2009-03-09 23:48:35 +00001337 switch (Arg.getKind()) {
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001338 case TemplateArgument::Null:
1339 assert(false && "Should never see a NULL template argument here");
1340 break;
1341
Douglas Gregor40808ce2009-03-09 23:48:35 +00001342 case TemplateArgument::Expression: {
1343 Expr *E = Arg.getAsExpr();
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001344 TemplateArgument Result;
1345 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
Douglas Gregorc15cb382009-02-09 23:23:08 +00001346 Invalid = true;
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001347 else
Anders Carlssonfb250522009-06-23 01:26:57 +00001348 Converted.Append(Result);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001349 break;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001350 }
1351
Douglas Gregor40808ce2009-03-09 23:48:35 +00001352 case TemplateArgument::Declaration:
1353 case TemplateArgument::Integral:
1354 // We've already checked this template argument, so just copy
1355 // it to the list of converted arguments.
Anders Carlssonfb250522009-06-23 01:26:57 +00001356 Converted.Append(Arg);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001357 break;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001358
Douglas Gregor40808ce2009-03-09 23:48:35 +00001359 case TemplateArgument::Type:
1360 // We have a non-type template parameter but the template
1361 // argument is a type.
1362
1363 // C++ [temp.arg]p2:
1364 // In a template-argument, an ambiguity between a type-id and
1365 // an expression is resolved to a type-id, regardless of the
1366 // form of the corresponding template-parameter.
1367 //
1368 // We warn specifically about this case, since it can be rather
1369 // confusing for users.
1370 if (Arg.getAsType()->isFunctionType())
1371 Diag(Arg.getLocation(), diag::err_template_arg_nontype_ambig)
1372 << Arg.getAsType();
1373 else
1374 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr);
1375 Diag((*Param)->getLocation(), diag::note_template_param_here);
1376 Invalid = true;
Anders Carlssond01b1da2009-06-15 17:04:53 +00001377 break;
1378
1379 case TemplateArgument::Pack:
1380 assert(0 && "FIXME: Implement!");
1381 break;
Douglas Gregor40808ce2009-03-09 23:48:35 +00001382 }
Douglas Gregorc15cb382009-02-09 23:23:08 +00001383 } else {
1384 // Check template template parameters.
1385 TemplateTemplateParmDecl *TempParm
1386 = cast<TemplateTemplateParmDecl>(*Param);
1387
Douglas Gregor40808ce2009-03-09 23:48:35 +00001388 switch (Arg.getKind()) {
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001389 case TemplateArgument::Null:
1390 assert(false && "Should never see a NULL template argument here");
1391 break;
1392
Douglas Gregor40808ce2009-03-09 23:48:35 +00001393 case TemplateArgument::Expression: {
1394 Expr *ArgExpr = Arg.getAsExpr();
1395 if (ArgExpr && isa<DeclRefExpr>(ArgExpr) &&
1396 isa<TemplateDecl>(cast<DeclRefExpr>(ArgExpr)->getDecl())) {
1397 if (CheckTemplateArgument(TempParm, cast<DeclRefExpr>(ArgExpr)))
1398 Invalid = true;
1399
1400 // Add the converted template argument.
Douglas Gregor7da97d02009-05-10 22:57:19 +00001401 Decl *D
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00001402 = cast<DeclRefExpr>(ArgExpr)->getDecl()->getCanonicalDecl();
Anders Carlssonfb250522009-06-23 01:26:57 +00001403 Converted.Append(TemplateArgument(Arg.getLocation(), D));
Douglas Gregor40808ce2009-03-09 23:48:35 +00001404 continue;
1405 }
1406 }
1407 // fall through
1408
1409 case TemplateArgument::Type: {
1410 // We have a template template parameter but the template
1411 // argument does not refer to a template.
1412 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
1413 Invalid = true;
1414 break;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001415 }
1416
Douglas Gregor40808ce2009-03-09 23:48:35 +00001417 case TemplateArgument::Declaration:
1418 // We've already checked this template argument, so just copy
1419 // it to the list of converted arguments.
Anders Carlssonfb250522009-06-23 01:26:57 +00001420 Converted.Append(Arg);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001421 break;
1422
1423 case TemplateArgument::Integral:
1424 assert(false && "Integral argument with template template parameter");
1425 break;
Anders Carlssond01b1da2009-06-15 17:04:53 +00001426
1427 case TemplateArgument::Pack:
1428 assert(0 && "FIXME: Implement!");
1429 break;
Douglas Gregor40808ce2009-03-09 23:48:35 +00001430 }
Douglas Gregorc15cb382009-02-09 23:23:08 +00001431 }
1432 }
1433
1434 return Invalid;
1435}
1436
1437/// \brief Check a template argument against its corresponding
1438/// template type parameter.
1439///
1440/// This routine implements the semantics of C++ [temp.arg.type]. It
1441/// returns true if an error occurred, and false otherwise.
1442bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
1443 QualType Arg, SourceLocation ArgLoc) {
1444 // C++ [temp.arg.type]p2:
1445 // A local type, a type with no linkage, an unnamed type or a type
1446 // compounded from any of these types shall not be used as a
1447 // template-argument for a template type-parameter.
1448 //
1449 // FIXME: Perform the recursive and no-linkage type checks.
1450 const TagType *Tag = 0;
1451 if (const EnumType *EnumT = Arg->getAsEnumType())
1452 Tag = EnumT;
Ted Kremenek6217b802009-07-29 21:53:49 +00001453 else if (const RecordType *RecordT = Arg->getAs<RecordType>())
Douglas Gregorc15cb382009-02-09 23:23:08 +00001454 Tag = RecordT;
1455 if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod())
1456 return Diag(ArgLoc, diag::err_template_arg_local_type)
1457 << QualType(Tag, 0);
Douglas Gregor98137532009-03-10 18:33:27 +00001458 else if (Tag && !Tag->getDecl()->getDeclName() &&
1459 !Tag->getDecl()->getTypedefForAnonDecl()) {
Douglas Gregorc15cb382009-02-09 23:23:08 +00001460 Diag(ArgLoc, diag::err_template_arg_unnamed_type);
1461 Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here);
1462 return true;
1463 }
1464
1465 return false;
1466}
1467
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001468/// \brief Checks whether the given template argument is the address
1469/// of an object or function according to C++ [temp.arg.nontype]p1.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001470bool Sema::CheckTemplateArgumentAddressOfObjectOrFunction(Expr *Arg,
1471 NamedDecl *&Entity) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001472 bool Invalid = false;
1473
1474 // See through any implicit casts we added to fix the type.
1475 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
1476 Arg = Cast->getSubExpr();
1477
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001478 // C++0x allows nullptr, and there's no further checking to be done for that.
1479 if (Arg->getType()->isNullPtrType())
1480 return false;
1481
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001482 // C++ [temp.arg.nontype]p1:
1483 //
1484 // A template-argument for a non-type, non-template
1485 // template-parameter shall be one of: [...]
1486 //
1487 // -- the address of an object or function with external
1488 // linkage, including function templates and function
1489 // template-ids but excluding non-static class members,
1490 // expressed as & id-expression where the & is optional if
1491 // the name refers to a function or array, or if the
1492 // corresponding template-parameter is a reference; or
1493 DeclRefExpr *DRE = 0;
1494
1495 // Ignore (and complain about) any excess parentheses.
1496 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
1497 if (!Invalid) {
1498 Diag(Arg->getSourceRange().getBegin(),
1499 diag::err_template_arg_extra_parens)
1500 << Arg->getSourceRange();
1501 Invalid = true;
1502 }
1503
1504 Arg = Parens->getSubExpr();
1505 }
1506
1507 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
1508 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
1509 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
1510 } else
1511 DRE = dyn_cast<DeclRefExpr>(Arg);
1512
1513 if (!DRE || !isa<ValueDecl>(DRE->getDecl()))
1514 return Diag(Arg->getSourceRange().getBegin(),
1515 diag::err_template_arg_not_object_or_func_form)
1516 << Arg->getSourceRange();
1517
1518 // Cannot refer to non-static data members
1519 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl()))
1520 return Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
1521 << Field << Arg->getSourceRange();
1522
1523 // Cannot refer to non-static member functions
1524 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
1525 if (!Method->isStatic())
1526 return Diag(Arg->getSourceRange().getBegin(),
1527 diag::err_template_arg_method)
1528 << Method << Arg->getSourceRange();
1529
1530 // Functions must have external linkage.
1531 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
1532 if (Func->getStorageClass() == FunctionDecl::Static) {
1533 Diag(Arg->getSourceRange().getBegin(),
1534 diag::err_template_arg_function_not_extern)
1535 << Func << Arg->getSourceRange();
1536 Diag(Func->getLocation(), diag::note_template_arg_internal_object)
1537 << true;
1538 return true;
1539 }
1540
1541 // Okay: we've named a function with external linkage.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001542 Entity = Func;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001543 return Invalid;
1544 }
1545
1546 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
1547 if (!Var->hasGlobalStorage()) {
1548 Diag(Arg->getSourceRange().getBegin(),
1549 diag::err_template_arg_object_not_extern)
1550 << Var << Arg->getSourceRange();
1551 Diag(Var->getLocation(), diag::note_template_arg_internal_object)
1552 << true;
1553 return true;
1554 }
1555
1556 // Okay: we've named an object with external linkage
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001557 Entity = Var;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001558 return Invalid;
1559 }
1560
1561 // We found something else, but we don't know specifically what it is.
1562 Diag(Arg->getSourceRange().getBegin(),
1563 diag::err_template_arg_not_object_or_func)
1564 << Arg->getSourceRange();
1565 Diag(DRE->getDecl()->getLocation(),
1566 diag::note_template_arg_refers_here);
1567 return true;
1568}
1569
1570/// \brief Checks whether the given template argument is a pointer to
1571/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001572bool
1573Sema::CheckTemplateArgumentPointerToMember(Expr *Arg, NamedDecl *&Member) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001574 bool Invalid = false;
1575
1576 // See through any implicit casts we added to fix the type.
1577 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
1578 Arg = Cast->getSubExpr();
1579
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001580 // C++0x allows nullptr, and there's no further checking to be done for that.
1581 if (Arg->getType()->isNullPtrType())
1582 return false;
1583
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001584 // C++ [temp.arg.nontype]p1:
1585 //
1586 // A template-argument for a non-type, non-template
1587 // template-parameter shall be one of: [...]
1588 //
1589 // -- a pointer to member expressed as described in 5.3.1.
1590 QualifiedDeclRefExpr *DRE = 0;
1591
1592 // Ignore (and complain about) any excess parentheses.
1593 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
1594 if (!Invalid) {
1595 Diag(Arg->getSourceRange().getBegin(),
1596 diag::err_template_arg_extra_parens)
1597 << Arg->getSourceRange();
1598 Invalid = true;
1599 }
1600
1601 Arg = Parens->getSubExpr();
1602 }
1603
1604 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg))
1605 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
1606 DRE = dyn_cast<QualifiedDeclRefExpr>(UnOp->getSubExpr());
1607
1608 if (!DRE)
1609 return Diag(Arg->getSourceRange().getBegin(),
1610 diag::err_template_arg_not_pointer_to_member_form)
1611 << Arg->getSourceRange();
1612
1613 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
1614 assert((isa<FieldDecl>(DRE->getDecl()) ||
1615 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
1616 "Only non-static member pointers can make it here");
1617
1618 // Okay: this is the address of a non-static member, and therefore
1619 // a member pointer constant.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001620 Member = DRE->getDecl();
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001621 return Invalid;
1622 }
1623
1624 // We found something else, but we don't know specifically what it is.
1625 Diag(Arg->getSourceRange().getBegin(),
1626 diag::err_template_arg_not_pointer_to_member_form)
1627 << Arg->getSourceRange();
1628 Diag(DRE->getDecl()->getLocation(),
1629 diag::note_template_arg_refers_here);
1630 return true;
1631}
1632
Douglas Gregorc15cb382009-02-09 23:23:08 +00001633/// \brief Check a template argument against its corresponding
1634/// non-type template parameter.
1635///
Douglas Gregor2943aed2009-03-03 04:44:36 +00001636/// This routine implements the semantics of C++ [temp.arg.nontype].
1637/// It returns true if an error occurred, and false otherwise. \p
1638/// InstantiatedParamType is the type of the non-type template
1639/// parameter after it has been instantiated.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001640///
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001641/// If no error was detected, Converted receives the converted template argument.
Douglas Gregorc15cb382009-02-09 23:23:08 +00001642bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Douglas Gregor2943aed2009-03-03 04:44:36 +00001643 QualType InstantiatedParamType, Expr *&Arg,
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001644 TemplateArgument &Converted) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00001645 SourceLocation StartLoc = Arg->getSourceRange().getBegin();
1646
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001647 // If either the parameter has a dependent type or the argument is
1648 // type-dependent, there's nothing we can check now.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001649 // FIXME: Add template argument to Converted!
Douglas Gregor40808ce2009-03-09 23:48:35 +00001650 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
1651 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001652 Converted = TemplateArgument(Arg);
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001653 return false;
Douglas Gregor40808ce2009-03-09 23:48:35 +00001654 }
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001655
1656 // C++ [temp.arg.nontype]p5:
1657 // The following conversions are performed on each expression used
1658 // as a non-type template-argument. If a non-type
1659 // template-argument cannot be converted to the type of the
1660 // corresponding template-parameter then the program is
1661 // ill-formed.
1662 //
1663 // -- for a non-type template-parameter of integral or
1664 // enumeration type, integral promotions (4.5) and integral
1665 // conversions (4.7) are applied.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001666 QualType ParamType = InstantiatedParamType;
Douglas Gregora35284b2009-02-11 00:19:33 +00001667 QualType ArgType = Arg->getType();
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001668 if (ParamType->isIntegralType() || ParamType->isEnumeralType()) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001669 // C++ [temp.arg.nontype]p1:
1670 // A template-argument for a non-type, non-template
1671 // template-parameter shall be one of:
1672 //
1673 // -- an integral constant-expression of integral or enumeration
1674 // type; or
1675 // -- the name of a non-type template-parameter; or
1676 SourceLocation NonConstantLoc;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001677 llvm::APSInt Value;
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001678 if (!ArgType->isIntegralType() && !ArgType->isEnumeralType()) {
1679 Diag(Arg->getSourceRange().getBegin(),
1680 diag::err_template_arg_not_integral_or_enumeral)
1681 << ArgType << Arg->getSourceRange();
1682 Diag(Param->getLocation(), diag::note_template_param_here);
1683 return true;
1684 } else if (!Arg->isValueDependent() &&
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001685 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001686 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
1687 << ArgType << Arg->getSourceRange();
1688 return true;
1689 }
1690
1691 // FIXME: We need some way to more easily get the unqualified form
1692 // of the types without going all the way to the
1693 // canonical type.
1694 if (Context.getCanonicalType(ParamType).getCVRQualifiers())
1695 ParamType = Context.getCanonicalType(ParamType).getUnqualifiedType();
1696 if (Context.getCanonicalType(ArgType).getCVRQualifiers())
1697 ArgType = Context.getCanonicalType(ArgType).getUnqualifiedType();
1698
1699 // Try to convert the argument to the parameter's type.
1700 if (ParamType == ArgType) {
1701 // Okay: no conversion necessary
1702 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
1703 !ParamType->isEnumeralType()) {
1704 // This is an integral promotion or conversion.
1705 ImpCastExprToType(Arg, ParamType);
1706 } else {
1707 // We can't perform this conversion.
1708 Diag(Arg->getSourceRange().getBegin(),
1709 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00001710 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001711 Diag(Param->getLocation(), diag::note_template_param_here);
1712 return true;
1713 }
1714
Douglas Gregorf80a9d52009-03-14 00:20:21 +00001715 QualType IntegerType = Context.getCanonicalType(ParamType);
1716 if (const EnumType *Enum = IntegerType->getAsEnumType())
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001717 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregorf80a9d52009-03-14 00:20:21 +00001718
1719 if (!Arg->isValueDependent()) {
1720 // Check that an unsigned parameter does not receive a negative
1721 // value.
1722 if (IntegerType->isUnsignedIntegerType()
1723 && (Value.isSigned() && Value.isNegative())) {
1724 Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_negative)
1725 << Value.toString(10) << Param->getType()
1726 << Arg->getSourceRange();
1727 Diag(Param->getLocation(), diag::note_template_param_here);
1728 return true;
1729 }
1730
1731 // Check that we don't overflow the template parameter type.
1732 unsigned AllowedBits = Context.getTypeSize(IntegerType);
1733 if (Value.getActiveBits() > AllowedBits) {
1734 Diag(Arg->getSourceRange().getBegin(),
1735 diag::err_template_arg_too_large)
1736 << Value.toString(10) << Param->getType()
1737 << Arg->getSourceRange();
1738 Diag(Param->getLocation(), diag::note_template_param_here);
1739 return true;
1740 }
1741
1742 if (Value.getBitWidth() != AllowedBits)
1743 Value.extOrTrunc(AllowedBits);
1744 Value.setIsSigned(IntegerType->isSignedIntegerType());
1745 }
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001746
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001747 // Add the value of this argument to the list of converted
1748 // arguments. We use the bitwidth and signedness of the template
1749 // parameter.
1750 if (Arg->isValueDependent()) {
1751 // The argument is value-dependent. Create a new
1752 // TemplateArgument with the converted expression.
1753 Converted = TemplateArgument(Arg);
1754 return false;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001755 }
1756
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001757 Converted = TemplateArgument(StartLoc, Value,
1758 ParamType->isEnumeralType() ? ParamType
1759 : IntegerType);
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001760 return false;
1761 }
Douglas Gregora35284b2009-02-11 00:19:33 +00001762
Douglas Gregorb86b0572009-02-11 01:18:59 +00001763 // Handle pointer-to-function, reference-to-function, and
1764 // pointer-to-member-function all in (roughly) the same way.
1765 if (// -- For a non-type template-parameter of type pointer to
1766 // function, only the function-to-pointer conversion (4.3) is
1767 // applied. If the template-argument represents a set of
1768 // overloaded functions (or a pointer to such), the matching
1769 // function is selected from the set (13.4).
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001770 // In C++0x, any std::nullptr_t value can be converted.
Douglas Gregorb86b0572009-02-11 01:18:59 +00001771 (ParamType->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00001772 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregorb86b0572009-02-11 01:18:59 +00001773 // -- For a non-type template-parameter of type reference to
1774 // function, no conversions apply. If the template-argument
1775 // represents a set of overloaded functions, the matching
1776 // function is selected from the set (13.4).
1777 (ParamType->isReferenceType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00001778 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregorb86b0572009-02-11 01:18:59 +00001779 // -- For a non-type template-parameter of type pointer to
1780 // member function, no conversions apply. If the
1781 // template-argument represents a set of overloaded member
1782 // functions, the matching member function is selected from
1783 // the set (13.4).
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001784 // Again, C++0x allows a std::nullptr_t value.
Douglas Gregorb86b0572009-02-11 01:18:59 +00001785 (ParamType->isMemberPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00001786 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregorb86b0572009-02-11 01:18:59 +00001787 ->isFunctionType())) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001788 if (Context.hasSameUnqualifiedType(ArgType,
1789 ParamType.getNonReferenceType())) {
Douglas Gregora35284b2009-02-11 00:19:33 +00001790 // We don't have to do anything: the types already match.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001791 } else if (ArgType->isNullPtrType() && (ParamType->isPointerType() ||
1792 ParamType->isMemberPointerType())) {
1793 ArgType = ParamType;
1794 ImpCastExprToType(Arg, ParamType);
Douglas Gregorb86b0572009-02-11 01:18:59 +00001795 } else if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregora35284b2009-02-11 00:19:33 +00001796 ArgType = Context.getPointerType(ArgType);
1797 ImpCastExprToType(Arg, ArgType);
1798 } else if (FunctionDecl *Fn
1799 = ResolveAddressOfOverloadedFunction(Arg, ParamType, true)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001800 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
1801 return true;
1802
Douglas Gregora35284b2009-02-11 00:19:33 +00001803 FixOverloadedFunctionReference(Arg, Fn);
1804 ArgType = Arg->getType();
Douglas Gregorb86b0572009-02-11 01:18:59 +00001805 if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregora35284b2009-02-11 00:19:33 +00001806 ArgType = Context.getPointerType(Arg->getType());
1807 ImpCastExprToType(Arg, ArgType);
1808 }
1809 }
1810
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001811 if (!Context.hasSameUnqualifiedType(ArgType,
1812 ParamType.getNonReferenceType())) {
Douglas Gregora35284b2009-02-11 00:19:33 +00001813 // We can't perform this conversion.
1814 Diag(Arg->getSourceRange().getBegin(),
1815 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00001816 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregora35284b2009-02-11 00:19:33 +00001817 Diag(Param->getLocation(), diag::note_template_param_here);
1818 return true;
1819 }
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001820
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001821 if (ParamType->isMemberPointerType()) {
1822 NamedDecl *Member = 0;
1823 if (CheckTemplateArgumentPointerToMember(Arg, Member))
1824 return true;
1825
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00001826 if (Member)
1827 Member = cast<NamedDecl>(Member->getCanonicalDecl());
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001828 Converted = TemplateArgument(StartLoc, Member);
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001829 return false;
1830 }
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001831
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001832 NamedDecl *Entity = 0;
1833 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1834 return true;
1835
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00001836 if (Entity)
1837 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001838 Converted = TemplateArgument(StartLoc, Entity);
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001839 return false;
Douglas Gregora35284b2009-02-11 00:19:33 +00001840 }
1841
Chris Lattnerfe90de72009-02-20 21:37:53 +00001842 if (ParamType->isPointerType()) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00001843 // -- for a non-type template-parameter of type pointer to
1844 // object, qualification conversions (4.4) and the
1845 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001846 // C++0x also allows a value of std::nullptr_t.
Ted Kremenek6217b802009-07-29 21:53:49 +00001847 assert(ParamType->getAs<PointerType>()->getPointeeType()->isObjectType() &&
Douglas Gregorb86b0572009-02-11 01:18:59 +00001848 "Only object pointers allowed here");
Douglas Gregorf684e6e2009-02-11 00:44:29 +00001849
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001850 if (ArgType->isNullPtrType()) {
1851 ArgType = ParamType;
1852 ImpCastExprToType(Arg, ParamType);
1853 } else if (ArgType->isArrayType()) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00001854 ArgType = Context.getArrayDecayedType(ArgType);
1855 ImpCastExprToType(Arg, ArgType);
Douglas Gregorf684e6e2009-02-11 00:44:29 +00001856 }
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001857
Douglas Gregorb86b0572009-02-11 01:18:59 +00001858 if (IsQualificationConversion(ArgType, ParamType)) {
1859 ArgType = ParamType;
1860 ImpCastExprToType(Arg, ParamType);
1861 }
1862
Douglas Gregor8e6563b2009-02-11 18:22:40 +00001863 if (!Context.hasSameUnqualifiedType(ArgType, ParamType)) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00001864 // 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 Gregorb86b0572009-02-11 01:18:59 +00001868 Diag(Param->getLocation(), diag::note_template_param_here);
1869 return true;
1870 }
1871
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001872 NamedDecl *Entity = 0;
1873 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1874 return true;
1875
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00001876 if (Entity)
1877 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001878 Converted = TemplateArgument(StartLoc, Entity);
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001879 return false;
Douglas Gregorf684e6e2009-02-11 00:44:29 +00001880 }
Douglas Gregorb86b0572009-02-11 01:18:59 +00001881
Ted Kremenek6217b802009-07-29 21:53:49 +00001882 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00001883 // -- For a non-type template-parameter of type reference to
1884 // object, no conversions apply. The type referred to by the
1885 // reference may be more cv-qualified than the (otherwise
1886 // identical) type of the template-argument. The
1887 // template-parameter is bound directly to the
1888 // template-argument, which must be an lvalue.
Douglas Gregorbad0e652009-03-24 20:32:41 +00001889 assert(ParamRefType->getPointeeType()->isObjectType() &&
Douglas Gregorb86b0572009-02-11 01:18:59 +00001890 "Only object references allowed here");
Douglas Gregorf684e6e2009-02-11 00:44:29 +00001891
Douglas Gregor8e6563b2009-02-11 18:22:40 +00001892 if (!Context.hasSameUnqualifiedType(ParamRefType->getPointeeType(), ArgType)) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00001893 Diag(Arg->getSourceRange().getBegin(),
1894 diag::err_template_arg_no_ref_bind)
Douglas Gregor2943aed2009-03-03 04:44:36 +00001895 << InstantiatedParamType << Arg->getType()
Douglas Gregorb86b0572009-02-11 01:18:59 +00001896 << Arg->getSourceRange();
1897 Diag(Param->getLocation(), diag::note_template_param_here);
1898 return true;
1899 }
1900
1901 unsigned ParamQuals
1902 = Context.getCanonicalType(ParamType).getCVRQualifiers();
1903 unsigned ArgQuals = Context.getCanonicalType(ArgType).getCVRQualifiers();
1904
1905 if ((ParamQuals | ArgQuals) != ParamQuals) {
1906 Diag(Arg->getSourceRange().getBegin(),
1907 diag::err_template_arg_ref_bind_ignores_quals)
Douglas Gregor2943aed2009-03-03 04:44:36 +00001908 << InstantiatedParamType << Arg->getType()
Douglas Gregorb86b0572009-02-11 01:18:59 +00001909 << Arg->getSourceRange();
1910 Diag(Param->getLocation(), diag::note_template_param_here);
1911 return true;
1912 }
1913
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001914 NamedDecl *Entity = 0;
1915 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1916 return true;
1917
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00001918 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001919 Converted = TemplateArgument(StartLoc, Entity);
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001920 return false;
Douglas Gregorb86b0572009-02-11 01:18:59 +00001921 }
Douglas Gregor658bbb52009-02-11 16:16:59 +00001922
1923 // -- For a non-type template-parameter of type pointer to data
1924 // member, qualification conversions (4.4) are applied.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001925 // C++0x allows std::nullptr_t values.
Douglas Gregor658bbb52009-02-11 16:16:59 +00001926 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
1927
Douglas Gregor8e6563b2009-02-11 18:22:40 +00001928 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
Douglas Gregor658bbb52009-02-11 16:16:59 +00001929 // Types match exactly: nothing more to do here.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001930 } else if (ArgType->isNullPtrType()) {
1931 ImpCastExprToType(Arg, ParamType);
Douglas Gregor658bbb52009-02-11 16:16:59 +00001932 } else if (IsQualificationConversion(ArgType, ParamType)) {
1933 ImpCastExprToType(Arg, ParamType);
1934 } else {
1935 // We can't perform this conversion.
1936 Diag(Arg->getSourceRange().getBegin(),
1937 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00001938 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor658bbb52009-02-11 16:16:59 +00001939 Diag(Param->getLocation(), diag::note_template_param_here);
1940 return true;
1941 }
1942
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001943 NamedDecl *Member = 0;
1944 if (CheckTemplateArgumentPointerToMember(Arg, Member))
1945 return true;
1946
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00001947 if (Member)
1948 Member = cast<NamedDecl>(Member->getCanonicalDecl());
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001949 Converted = TemplateArgument(StartLoc, Member);
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001950 return false;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001951}
1952
1953/// \brief Check a template argument against its corresponding
1954/// template template parameter.
1955///
1956/// This routine implements the semantics of C++ [temp.arg.template].
1957/// It returns true if an error occurred, and false otherwise.
1958bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
1959 DeclRefExpr *Arg) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00001960 assert(isa<TemplateDecl>(Arg->getDecl()) && "Only template decls allowed");
1961 TemplateDecl *Template = cast<TemplateDecl>(Arg->getDecl());
1962
1963 // C++ [temp.arg.template]p1:
1964 // A template-argument for a template template-parameter shall be
1965 // the name of a class template, expressed as id-expression. Only
1966 // primary class templates are considered when matching the
1967 // template template argument with the corresponding parameter;
1968 // partial specializations are not considered even if their
1969 // parameter lists match that of the template template parameter.
Douglas Gregorba1ecb52009-06-12 19:43:02 +00001970 //
1971 // Note that we also allow template template parameters here, which
1972 // will happen when we are dealing with, e.g., class template
1973 // partial specializations.
1974 if (!isa<ClassTemplateDecl>(Template) &&
1975 !isa<TemplateTemplateParmDecl>(Template)) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00001976 assert(isa<FunctionTemplateDecl>(Template) &&
1977 "Only function templates are possible here");
Douglas Gregore53060f2009-06-25 22:08:12 +00001978 Diag(Arg->getLocStart(), diag::err_template_arg_not_class_template);
1979 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
Douglas Gregordd0574e2009-02-10 00:24:35 +00001980 << Template;
1981 }
1982
1983 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
1984 Param->getTemplateParameters(),
1985 true, true,
1986 Arg->getSourceRange().getBegin());
Douglas Gregorc15cb382009-02-09 23:23:08 +00001987}
1988
Douglas Gregorddc29e12009-02-06 22:42:48 +00001989/// \brief Determine whether the given template parameter lists are
1990/// equivalent.
1991///
1992/// \param New The new template parameter list, typically written in the
1993/// source code as part of a new template declaration.
1994///
1995/// \param Old The old template parameter list, typically found via
1996/// name lookup of the template declared with this template parameter
1997/// list.
1998///
1999/// \param Complain If true, this routine will produce a diagnostic if
2000/// the template parameter lists are not equivalent.
2001///
Douglas Gregordd0574e2009-02-10 00:24:35 +00002002/// \param IsTemplateTemplateParm If true, this routine is being
2003/// called to compare the template parameter lists of a template
2004/// template parameter.
2005///
2006/// \param TemplateArgLoc If this source location is valid, then we
2007/// are actually checking the template parameter list of a template
2008/// argument (New) against the template parameter list of its
2009/// corresponding template template parameter (Old). We produce
2010/// slightly different diagnostics in this scenario.
2011///
Douglas Gregorddc29e12009-02-06 22:42:48 +00002012/// \returns True if the template parameter lists are equal, false
2013/// otherwise.
2014bool
2015Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
2016 TemplateParameterList *Old,
2017 bool Complain,
Douglas Gregordd0574e2009-02-10 00:24:35 +00002018 bool IsTemplateTemplateParm,
2019 SourceLocation TemplateArgLoc) {
Douglas Gregorddc29e12009-02-06 22:42:48 +00002020 if (Old->size() != New->size()) {
2021 if (Complain) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00002022 unsigned NextDiag = diag::err_template_param_list_different_arity;
2023 if (TemplateArgLoc.isValid()) {
2024 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
2025 NextDiag = diag::note_template_param_list_different_arity;
2026 }
2027 Diag(New->getTemplateLoc(), NextDiag)
2028 << (New->size() > Old->size())
2029 << IsTemplateTemplateParm
2030 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
Douglas Gregorddc29e12009-02-06 22:42:48 +00002031 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
2032 << IsTemplateTemplateParm
2033 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
2034 }
2035
2036 return false;
2037 }
2038
2039 for (TemplateParameterList::iterator OldParm = Old->begin(),
2040 OldParmEnd = Old->end(), NewParm = New->begin();
2041 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
2042 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
Douglas Gregor34d1dc92009-06-24 16:50:40 +00002043 if (Complain) {
2044 unsigned NextDiag = diag::err_template_param_different_kind;
2045 if (TemplateArgLoc.isValid()) {
2046 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
2047 NextDiag = diag::note_template_param_different_kind;
2048 }
2049 Diag((*NewParm)->getLocation(), NextDiag)
2050 << IsTemplateTemplateParm;
2051 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
2052 << IsTemplateTemplateParm;
Douglas Gregordd0574e2009-02-10 00:24:35 +00002053 }
Douglas Gregorddc29e12009-02-06 22:42:48 +00002054 return false;
2055 }
2056
2057 if (isa<TemplateTypeParmDecl>(*OldParm)) {
2058 // Okay; all template type parameters are equivalent (since we
Douglas Gregordd0574e2009-02-10 00:24:35 +00002059 // know we're at the same index).
2060#if 0
Mike Stump390b4cc2009-05-16 07:39:55 +00002061 // FIXME: Enable this code in debug mode *after* we properly go through
2062 // and "instantiate" the template parameter lists of template template
2063 // parameters. It's only after this instantiation that (1) any dependent
2064 // types within the template parameter list of the template template
2065 // parameter can be checked, and (2) the template type parameter depths
Douglas Gregordd0574e2009-02-10 00:24:35 +00002066 // will match up.
Douglas Gregorddc29e12009-02-06 22:42:48 +00002067 QualType OldParmType
2068 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*OldParm));
2069 QualType NewParmType
2070 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*NewParm));
2071 assert(Context.getCanonicalType(OldParmType) ==
2072 Context.getCanonicalType(NewParmType) &&
2073 "type parameter mismatch?");
2074#endif
2075 } else if (NonTypeTemplateParmDecl *OldNTTP
2076 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
2077 // The types of non-type template parameters must agree.
2078 NonTypeTemplateParmDecl *NewNTTP
2079 = cast<NonTypeTemplateParmDecl>(*NewParm);
2080 if (Context.getCanonicalType(OldNTTP->getType()) !=
2081 Context.getCanonicalType(NewNTTP->getType())) {
2082 if (Complain) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00002083 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
2084 if (TemplateArgLoc.isValid()) {
2085 Diag(TemplateArgLoc,
2086 diag::err_template_arg_template_params_mismatch);
2087 NextDiag = diag::note_template_nontype_parm_different_type;
2088 }
2089 Diag(NewNTTP->getLocation(), NextDiag)
Douglas Gregorddc29e12009-02-06 22:42:48 +00002090 << NewNTTP->getType()
2091 << IsTemplateTemplateParm;
2092 Diag(OldNTTP->getLocation(),
2093 diag::note_template_nontype_parm_prev_declaration)
2094 << OldNTTP->getType();
2095 }
2096 return false;
2097 }
2098 } else {
2099 // The template parameter lists of template template
2100 // parameters must agree.
2101 // FIXME: Could we perform a faster "type" comparison here?
2102 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
2103 "Only template template parameters handled here");
2104 TemplateTemplateParmDecl *OldTTP
2105 = cast<TemplateTemplateParmDecl>(*OldParm);
2106 TemplateTemplateParmDecl *NewTTP
2107 = cast<TemplateTemplateParmDecl>(*NewParm);
2108 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
2109 OldTTP->getTemplateParameters(),
2110 Complain,
Douglas Gregordd0574e2009-02-10 00:24:35 +00002111 /*IsTemplateTemplateParm=*/true,
2112 TemplateArgLoc))
Douglas Gregorddc29e12009-02-06 22:42:48 +00002113 return false;
2114 }
2115 }
2116
2117 return true;
2118}
2119
2120/// \brief Check whether a template can be declared within this scope.
2121///
2122/// If the template declaration is valid in this scope, returns
2123/// false. Otherwise, issues a diagnostic and returns true.
2124bool
Douglas Gregor05396e22009-08-25 17:23:04 +00002125Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
Douglas Gregorddc29e12009-02-06 22:42:48 +00002126 // Find the nearest enclosing declaration scope.
2127 while ((S->getFlags() & Scope::DeclScope) == 0 ||
2128 (S->getFlags() & Scope::TemplateParamScope) != 0)
2129 S = S->getParent();
2130
Douglas Gregorddc29e12009-02-06 22:42:48 +00002131 // C++ [temp]p2:
2132 // A template-declaration can appear only as a namespace scope or
2133 // class scope declaration.
2134 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
Eli Friedman1503f772009-07-31 01:43:05 +00002135 if (Ctx && isa<LinkageSpecDecl>(Ctx) &&
2136 cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
Douglas Gregor05396e22009-08-25 17:23:04 +00002137 return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
2138 << TemplateParams->getSourceRange();
Eli Friedman1503f772009-07-31 01:43:05 +00002139
2140 while (Ctx && isa<LinkageSpecDecl>(Ctx))
Douglas Gregorddc29e12009-02-06 22:42:48 +00002141 Ctx = Ctx->getParent();
Douglas Gregorddc29e12009-02-06 22:42:48 +00002142
2143 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
2144 return false;
2145
Douglas Gregor05396e22009-08-25 17:23:04 +00002146 return Diag(TemplateParams->getTemplateLoc(),
2147 diag::err_template_outside_namespace_or_class_scope)
2148 << TemplateParams->getSourceRange();
Douglas Gregorddc29e12009-02-06 22:42:48 +00002149}
Douglas Gregorcc636682009-02-17 23:15:12 +00002150
Douglas Gregorff668032009-05-13 18:28:20 +00002151/// \brief Check whether a class template specialization or explicit
2152/// instantiation in the current context is well-formed.
Douglas Gregor88b70942009-02-25 22:02:03 +00002153///
Douglas Gregorff668032009-05-13 18:28:20 +00002154/// This routine determines whether a class template specialization or
2155/// explicit instantiation can be declared in the current context
2156/// (C++ [temp.expl.spec]p2, C++0x [temp.explicit]p2) and emits
2157/// appropriate diagnostics if there was an error. It returns true if
2158// there was an error that we cannot recover from, and false otherwise.
Douglas Gregor88b70942009-02-25 22:02:03 +00002159bool
2160Sema::CheckClassTemplateSpecializationScope(ClassTemplateDecl *ClassTemplate,
2161 ClassTemplateSpecializationDecl *PrevDecl,
2162 SourceLocation TemplateNameLoc,
Douglas Gregorff668032009-05-13 18:28:20 +00002163 SourceRange ScopeSpecifierRange,
Douglas Gregor16df8502009-06-12 22:21:45 +00002164 bool PartialSpecialization,
Douglas Gregorff668032009-05-13 18:28:20 +00002165 bool ExplicitInstantiation) {
Douglas Gregor88b70942009-02-25 22:02:03 +00002166 // C++ [temp.expl.spec]p2:
2167 // An explicit specialization shall be declared in the namespace
2168 // of which the template is a member, or, for member templates, in
2169 // the namespace of which the enclosing class or enclosing class
2170 // template is a member. An explicit specialization of a member
2171 // function, member class or static data member of a class
2172 // template shall be declared in the namespace of which the class
2173 // template is a member. Such a declaration may also be a
2174 // definition. If the declaration is not a definition, the
2175 // specialization may be defined later in the name- space in which
2176 // the explicit specialization was declared, or in a namespace
2177 // that encloses the one in which the explicit specialization was
2178 // declared.
2179 if (CurContext->getLookupContext()->isFunctionOrMethod()) {
Douglas Gregor16df8502009-06-12 22:21:45 +00002180 int Kind = ExplicitInstantiation? 2 : PartialSpecialization? 1 : 0;
Douglas Gregor88b70942009-02-25 22:02:03 +00002181 Diag(TemplateNameLoc, diag::err_template_spec_decl_function_scope)
Douglas Gregor16df8502009-06-12 22:21:45 +00002182 << Kind << ClassTemplate;
Douglas Gregor88b70942009-02-25 22:02:03 +00002183 return true;
2184 }
2185
2186 DeclContext *DC = CurContext->getEnclosingNamespaceContext();
2187 DeclContext *TemplateContext
2188 = ClassTemplate->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregorff668032009-05-13 18:28:20 +00002189 if ((!PrevDecl || PrevDecl->getSpecializationKind() == TSK_Undeclared) &&
2190 !ExplicitInstantiation) {
Douglas Gregor88b70942009-02-25 22:02:03 +00002191 // There is no prior declaration of this entity, so this
2192 // specialization must be in the same context as the template
2193 // itself.
2194 if (DC != TemplateContext) {
2195 if (isa<TranslationUnitDecl>(TemplateContext))
2196 Diag(TemplateNameLoc, diag::err_template_spec_decl_out_of_scope_global)
Douglas Gregor16df8502009-06-12 22:21:45 +00002197 << PartialSpecialization
Douglas Gregor88b70942009-02-25 22:02:03 +00002198 << ClassTemplate << ScopeSpecifierRange;
2199 else if (isa<NamespaceDecl>(TemplateContext))
2200 Diag(TemplateNameLoc, diag::err_template_spec_decl_out_of_scope)
Douglas Gregor16df8502009-06-12 22:21:45 +00002201 << PartialSpecialization << ClassTemplate
2202 << cast<NamedDecl>(TemplateContext) << ScopeSpecifierRange;
Douglas Gregor88b70942009-02-25 22:02:03 +00002203
2204 Diag(ClassTemplate->getLocation(), diag::note_template_decl_here);
2205 }
2206
2207 return false;
2208 }
2209
2210 // We have a previous declaration of this entity. Make sure that
2211 // this redeclaration (or definition) occurs in an enclosing namespace.
2212 if (!CurContext->Encloses(TemplateContext)) {
Mike Stump390b4cc2009-05-16 07:39:55 +00002213 // FIXME: In C++98, we would like to turn these errors into warnings,
2214 // dependent on a -Wc++0x flag.
Douglas Gregorff668032009-05-13 18:28:20 +00002215 bool SuppressedDiag = false;
Douglas Gregor16df8502009-06-12 22:21:45 +00002216 int Kind = ExplicitInstantiation? 2 : PartialSpecialization? 1 : 0;
Douglas Gregorff668032009-05-13 18:28:20 +00002217 if (isa<TranslationUnitDecl>(TemplateContext)) {
2218 if (!ExplicitInstantiation || getLangOptions().CPlusPlus0x)
2219 Diag(TemplateNameLoc, diag::err_template_spec_redecl_global_scope)
Douglas Gregor16df8502009-06-12 22:21:45 +00002220 << Kind << ClassTemplate << ScopeSpecifierRange;
Douglas Gregorff668032009-05-13 18:28:20 +00002221 else
2222 SuppressedDiag = true;
2223 } else if (isa<NamespaceDecl>(TemplateContext)) {
2224 if (!ExplicitInstantiation || getLangOptions().CPlusPlus0x)
2225 Diag(TemplateNameLoc, diag::err_template_spec_redecl_out_of_scope)
Douglas Gregor16df8502009-06-12 22:21:45 +00002226 << Kind << ClassTemplate
Douglas Gregorff668032009-05-13 18:28:20 +00002227 << cast<NamedDecl>(TemplateContext) << ScopeSpecifierRange;
2228 else
2229 SuppressedDiag = true;
2230 }
Douglas Gregor88b70942009-02-25 22:02:03 +00002231
Douglas Gregorff668032009-05-13 18:28:20 +00002232 if (!SuppressedDiag)
2233 Diag(ClassTemplate->getLocation(), diag::note_template_decl_here);
Douglas Gregor88b70942009-02-25 22:02:03 +00002234 }
2235
2236 return false;
2237}
2238
Douglas Gregore94866f2009-06-12 21:21:02 +00002239/// \brief Check the non-type template arguments of a class template
2240/// partial specialization according to C++ [temp.class.spec]p9.
2241///
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002242/// \param TemplateParams the template parameters of the primary class
2243/// template.
2244///
2245/// \param TemplateArg the template arguments of the class template
2246/// partial specialization.
2247///
2248/// \param MirrorsPrimaryTemplate will be set true if the class
2249/// template partial specialization arguments are identical to the
2250/// implicit template arguments of the primary template. This is not
2251/// necessarily an error (C++0x), and it is left to the caller to diagnose
2252/// this condition when it is an error.
2253///
Douglas Gregore94866f2009-06-12 21:21:02 +00002254/// \returns true if there was an error, false otherwise.
2255bool Sema::CheckClassTemplatePartialSpecializationArgs(
2256 TemplateParameterList *TemplateParams,
Anders Carlsson6360be72009-06-13 18:20:51 +00002257 const TemplateArgumentListBuilder &TemplateArgs,
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002258 bool &MirrorsPrimaryTemplate) {
Douglas Gregore94866f2009-06-12 21:21:02 +00002259 // FIXME: the interface to this function will have to change to
2260 // accommodate variadic templates.
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002261 MirrorsPrimaryTemplate = true;
Anders Carlsson6360be72009-06-13 18:20:51 +00002262
Anders Carlssonfb250522009-06-23 01:26:57 +00002263 const TemplateArgument *ArgList = TemplateArgs.getFlatArguments();
Anders Carlsson6360be72009-06-13 18:20:51 +00002264
Douglas Gregore94866f2009-06-12 21:21:02 +00002265 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002266 // Determine whether the template argument list of the partial
2267 // specialization is identical to the implicit argument list of
2268 // the primary template. The caller may need to diagnostic this as
2269 // an error per C++ [temp.class.spec]p9b3.
2270 if (MirrorsPrimaryTemplate) {
2271 if (TemplateTypeParmDecl *TTP
2272 = dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(I))) {
2273 if (Context.getCanonicalType(Context.getTypeDeclType(TTP)) !=
Anders Carlsson6360be72009-06-13 18:20:51 +00002274 Context.getCanonicalType(ArgList[I].getAsType()))
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002275 MirrorsPrimaryTemplate = false;
2276 } else if (TemplateTemplateParmDecl *TTP
2277 = dyn_cast<TemplateTemplateParmDecl>(
2278 TemplateParams->getParam(I))) {
2279 // FIXME: We should settle on either Declaration storage or
2280 // Expression storage for template template parameters.
2281 TemplateTemplateParmDecl *ArgDecl
2282 = dyn_cast_or_null<TemplateTemplateParmDecl>(
Anders Carlsson6360be72009-06-13 18:20:51 +00002283 ArgList[I].getAsDecl());
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002284 if (!ArgDecl)
2285 if (DeclRefExpr *DRE
Anders Carlsson6360be72009-06-13 18:20:51 +00002286 = dyn_cast_or_null<DeclRefExpr>(ArgList[I].getAsExpr()))
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002287 ArgDecl = dyn_cast<TemplateTemplateParmDecl>(DRE->getDecl());
2288
2289 if (!ArgDecl ||
2290 ArgDecl->getIndex() != TTP->getIndex() ||
2291 ArgDecl->getDepth() != TTP->getDepth())
2292 MirrorsPrimaryTemplate = false;
2293 }
2294 }
2295
Douglas Gregore94866f2009-06-12 21:21:02 +00002296 NonTypeTemplateParmDecl *Param
2297 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002298 if (!Param) {
Douglas Gregore94866f2009-06-12 21:21:02 +00002299 continue;
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002300 }
2301
Anders Carlsson6360be72009-06-13 18:20:51 +00002302 Expr *ArgExpr = ArgList[I].getAsExpr();
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002303 if (!ArgExpr) {
2304 MirrorsPrimaryTemplate = false;
Douglas Gregore94866f2009-06-12 21:21:02 +00002305 continue;
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002306 }
Douglas Gregore94866f2009-06-12 21:21:02 +00002307
2308 // C++ [temp.class.spec]p8:
2309 // A non-type argument is non-specialized if it is the name of a
2310 // non-type parameter. All other non-type arguments are
2311 // specialized.
2312 //
2313 // Below, we check the two conditions that only apply to
2314 // specialized non-type arguments, so skip any non-specialized
2315 // arguments.
2316 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002317 if (NonTypeTemplateParmDecl *NTTP
2318 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl())) {
2319 if (MirrorsPrimaryTemplate &&
2320 (Param->getIndex() != NTTP->getIndex() ||
2321 Param->getDepth() != NTTP->getDepth()))
2322 MirrorsPrimaryTemplate = false;
2323
Douglas Gregore94866f2009-06-12 21:21:02 +00002324 continue;
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002325 }
Douglas Gregore94866f2009-06-12 21:21:02 +00002326
2327 // C++ [temp.class.spec]p9:
2328 // Within the argument list of a class template partial
2329 // specialization, the following restrictions apply:
2330 // -- A partially specialized non-type argument expression
2331 // shall not involve a template parameter of the partial
2332 // specialization except when the argument expression is a
2333 // simple identifier.
2334 if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
2335 Diag(ArgExpr->getLocStart(),
2336 diag::err_dependent_non_type_arg_in_partial_spec)
2337 << ArgExpr->getSourceRange();
2338 return true;
2339 }
2340
2341 // -- The type of a template parameter corresponding to a
2342 // specialized non-type argument shall not be dependent on a
2343 // parameter of the specialization.
2344 if (Param->getType()->isDependentType()) {
2345 Diag(ArgExpr->getLocStart(),
2346 diag::err_dependent_typed_non_type_arg_in_partial_spec)
2347 << Param->getType()
2348 << ArgExpr->getSourceRange();
2349 Diag(Param->getLocation(), diag::note_template_param_here);
2350 return true;
2351 }
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002352
2353 MirrorsPrimaryTemplate = false;
Douglas Gregore94866f2009-06-12 21:21:02 +00002354 }
2355
2356 return false;
2357}
2358
Douglas Gregor212e81c2009-03-25 00:13:59 +00002359Sema::DeclResult
John McCall0f434ec2009-07-31 02:45:11 +00002360Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
2361 TagUseKind TUK,
Douglas Gregorcc636682009-02-17 23:15:12 +00002362 SourceLocation KWLoc,
2363 const CXXScopeSpec &SS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00002364 TemplateTy TemplateD,
Douglas Gregorcc636682009-02-17 23:15:12 +00002365 SourceLocation TemplateNameLoc,
2366 SourceLocation LAngleLoc,
Douglas Gregor40808ce2009-03-09 23:48:35 +00002367 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregorcc636682009-02-17 23:15:12 +00002368 SourceLocation *TemplateArgLocs,
2369 SourceLocation RAngleLoc,
2370 AttributeList *Attr,
2371 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregorcc636682009-02-17 23:15:12 +00002372 // Find the class template we're specializing
Douglas Gregor7532dc62009-03-30 22:58:21 +00002373 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Douglas Gregorcc636682009-02-17 23:15:12 +00002374 ClassTemplateDecl *ClassTemplate
Douglas Gregor7532dc62009-03-30 22:58:21 +00002375 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
Douglas Gregorcc636682009-02-17 23:15:12 +00002376
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002377 bool isPartialSpecialization = false;
2378
Douglas Gregor88b70942009-02-25 22:02:03 +00002379 // Check the validity of the template headers that introduce this
2380 // template.
Douglas Gregor05396e22009-08-25 17:23:04 +00002381 TemplateParameterList *TemplateParams
2382 = MatchTemplateParametersToScopeSpecifier(TemplateNameLoc, SS,
2383 (TemplateParameterList**)TemplateParameterLists.get(),
2384 TemplateParameterLists.size());
2385 if (TemplateParams && TemplateParams->size() > 0) {
2386 isPartialSpecialization = true;
Douglas Gregor88b70942009-02-25 22:02:03 +00002387
Douglas Gregor05396e22009-08-25 17:23:04 +00002388 // C++ [temp.class.spec]p10:
2389 // The template parameter list of a specialization shall not
2390 // contain default template argument values.
2391 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
2392 Decl *Param = TemplateParams->getParam(I);
2393 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
2394 if (TTP->hasDefaultArgument()) {
2395 Diag(TTP->getDefaultArgumentLoc(),
2396 diag::err_default_arg_in_partial_spec);
2397 TTP->setDefaultArgument(QualType(), SourceLocation(), false);
2398 }
2399 } else if (NonTypeTemplateParmDecl *NTTP
2400 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2401 if (Expr *DefArg = NTTP->getDefaultArgument()) {
2402 Diag(NTTP->getDefaultArgumentLoc(),
2403 diag::err_default_arg_in_partial_spec)
2404 << DefArg->getSourceRange();
2405 NTTP->setDefaultArgument(0);
2406 DefArg->Destroy(Context);
2407 }
2408 } else {
2409 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
2410 if (Expr *DefArg = TTP->getDefaultArgument()) {
2411 Diag(TTP->getDefaultArgumentLoc(),
2412 diag::err_default_arg_in_partial_spec)
2413 << DefArg->getSourceRange();
2414 TTP->setDefaultArgument(0);
2415 DefArg->Destroy(Context);
Douglas Gregorba1ecb52009-06-12 19:43:02 +00002416 }
2417 }
2418 }
Douglas Gregor05396e22009-08-25 17:23:04 +00002419 } else if (!TemplateParams)
2420 Diag(KWLoc, diag::err_template_spec_needs_header)
2421 << CodeModificationHint::CreateInsertion(KWLoc, "template<> ");
Douglas Gregor88b70942009-02-25 22:02:03 +00002422
Douglas Gregorcc636682009-02-17 23:15:12 +00002423 // Check that the specialization uses the same tag kind as the
2424 // original template.
2425 TagDecl::TagKind Kind;
2426 switch (TagSpec) {
2427 default: assert(0 && "Unknown tag type!");
2428 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2429 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2430 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2431 }
Douglas Gregor501c5ce2009-05-14 16:41:31 +00002432 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
2433 Kind, KWLoc,
2434 *ClassTemplate->getIdentifier())) {
Douglas Gregora3a83512009-04-01 23:51:29 +00002435 Diag(KWLoc, diag::err_use_with_wrong_tag)
2436 << ClassTemplate
2437 << CodeModificationHint::CreateReplacement(KWLoc,
2438 ClassTemplate->getTemplatedDecl()->getKindName());
Douglas Gregorcc636682009-02-17 23:15:12 +00002439 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
2440 diag::note_previous_use);
2441 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
2442 }
2443
Douglas Gregor40808ce2009-03-09 23:48:35 +00002444 // Translate the parser's template argument list in our AST format.
2445 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
2446 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
2447
Douglas Gregorcc636682009-02-17 23:15:12 +00002448 // Check that the template argument list is well-formed for this
2449 // template.
Anders Carlssonfb250522009-06-23 01:26:57 +00002450 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
2451 TemplateArgs.size());
Douglas Gregorcc636682009-02-17 23:15:12 +00002452 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
Anders Carlsson6360be72009-06-13 18:20:51 +00002453 TemplateArgs.data(), TemplateArgs.size(),
Douglas Gregor16134c62009-07-01 00:28:38 +00002454 RAngleLoc, false, Converted))
Douglas Gregor212e81c2009-03-25 00:13:59 +00002455 return true;
Douglas Gregorcc636682009-02-17 23:15:12 +00002456
Anders Carlssonfb250522009-06-23 01:26:57 +00002457 assert((Converted.structuredSize() ==
Douglas Gregorcc636682009-02-17 23:15:12 +00002458 ClassTemplate->getTemplateParameters()->size()) &&
2459 "Converted template argument list is too short!");
2460
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002461 // Find the class template (partial) specialization declaration that
Douglas Gregorcc636682009-02-17 23:15:12 +00002462 // corresponds to these arguments.
2463 llvm::FoldingSetNodeID ID;
Douglas Gregorba1ecb52009-06-12 19:43:02 +00002464 if (isPartialSpecialization) {
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002465 bool MirrorsPrimaryTemplate;
Douglas Gregore94866f2009-06-12 21:21:02 +00002466 if (CheckClassTemplatePartialSpecializationArgs(
2467 ClassTemplate->getTemplateParameters(),
Anders Carlssonfb250522009-06-23 01:26:57 +00002468 Converted, MirrorsPrimaryTemplate))
Douglas Gregore94866f2009-06-12 21:21:02 +00002469 return true;
2470
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002471 if (MirrorsPrimaryTemplate) {
2472 // C++ [temp.class.spec]p9b3:
2473 //
2474 // -- The argument list of the specialization shall not be identical
2475 // to the implicit argument list of the primary template.
2476 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
John McCall0f434ec2009-07-31 02:45:11 +00002477 << (TUK == TUK_Definition)
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002478 << CodeModificationHint::CreateRemoval(SourceRange(LAngleLoc,
2479 RAngleLoc));
John McCall0f434ec2009-07-31 02:45:11 +00002480 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002481 ClassTemplate->getIdentifier(),
2482 TemplateNameLoc,
2483 Attr,
Douglas Gregor05396e22009-08-25 17:23:04 +00002484 TemplateParams,
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002485 AS_none);
2486 }
2487
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002488 // FIXME: Template parameter list matters, too
Anders Carlsson1c5976e2009-06-05 03:43:12 +00002489 ClassTemplatePartialSpecializationDecl::Profile(ID,
Anders Carlssonfb250522009-06-23 01:26:57 +00002490 Converted.getFlatArguments(),
Douglas Gregor828e2262009-07-29 16:09:57 +00002491 Converted.flatSize(),
2492 Context);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00002493 } else
Anders Carlsson1c5976e2009-06-05 03:43:12 +00002494 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlssonfb250522009-06-23 01:26:57 +00002495 Converted.getFlatArguments(),
Douglas Gregor828e2262009-07-29 16:09:57 +00002496 Converted.flatSize(),
2497 Context);
Douglas Gregorcc636682009-02-17 23:15:12 +00002498 void *InsertPos = 0;
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002499 ClassTemplateSpecializationDecl *PrevDecl = 0;
2500
2501 if (isPartialSpecialization)
2502 PrevDecl
2503 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
2504 InsertPos);
2505 else
2506 PrevDecl
2507 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorcc636682009-02-17 23:15:12 +00002508
2509 ClassTemplateSpecializationDecl *Specialization = 0;
2510
Douglas Gregor88b70942009-02-25 22:02:03 +00002511 // Check whether we can declare a class template specialization in
2512 // the current scope.
2513 if (CheckClassTemplateSpecializationScope(ClassTemplate, PrevDecl,
2514 TemplateNameLoc,
Douglas Gregorff668032009-05-13 18:28:20 +00002515 SS.getRange(),
Douglas Gregor16df8502009-06-12 22:21:45 +00002516 isPartialSpecialization,
Douglas Gregorff668032009-05-13 18:28:20 +00002517 /*ExplicitInstantiation=*/false))
Douglas Gregor212e81c2009-03-25 00:13:59 +00002518 return true;
Douglas Gregor88b70942009-02-25 22:02:03 +00002519
Douglas Gregorb88e8882009-07-30 17:40:51 +00002520 // The canonical type
2521 QualType CanonType;
Douglas Gregorcc636682009-02-17 23:15:12 +00002522 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
2523 // Since the only prior class template specialization with these
2524 // arguments was referenced but not declared, reuse that
2525 // declaration node as our own, updating its source location to
2526 // reflect our new declaration.
Douglas Gregorcc636682009-02-17 23:15:12 +00002527 Specialization = PrevDecl;
Douglas Gregor6bc9f7e2009-02-25 22:18:32 +00002528 Specialization->setLocation(TemplateNameLoc);
Douglas Gregorcc636682009-02-17 23:15:12 +00002529 PrevDecl = 0;
Douglas Gregorb88e8882009-07-30 17:40:51 +00002530 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002531 } else if (isPartialSpecialization) {
Douglas Gregorb88e8882009-07-30 17:40:51 +00002532 // Build the canonical type that describes the converted template
2533 // arguments of the class template partial specialization.
2534 CanonType = Context.getTemplateSpecializationType(
2535 TemplateName(ClassTemplate),
2536 Converted.getFlatArguments(),
2537 Converted.flatSize());
2538
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002539 // Create a new class template partial specialization declaration node.
2540 TemplateParameterList *TemplateParams
2541 = static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
2542 ClassTemplatePartialSpecializationDecl *PrevPartial
2543 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
2544 ClassTemplatePartialSpecializationDecl *Partial
2545 = ClassTemplatePartialSpecializationDecl::Create(Context,
2546 ClassTemplate->getDeclContext(),
Anders Carlsson91fdf6f2009-06-05 04:06:48 +00002547 TemplateNameLoc,
2548 TemplateParams,
2549 ClassTemplate,
Anders Carlssonfb250522009-06-23 01:26:57 +00002550 Converted,
Anders Carlsson91fdf6f2009-06-05 04:06:48 +00002551 PrevPartial);
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002552
2553 if (PrevPartial) {
2554 ClassTemplate->getPartialSpecializations().RemoveNode(PrevPartial);
2555 ClassTemplate->getPartialSpecializations().GetOrInsertNode(Partial);
2556 } else {
2557 ClassTemplate->getPartialSpecializations().InsertNode(Partial, InsertPos);
2558 }
2559 Specialization = Partial;
Douglas Gregor031a5882009-06-13 00:26:55 +00002560
2561 // Check that all of the template parameters of the class template
2562 // partial specialization are deducible from the template
2563 // arguments. If not, this class template partial specialization
2564 // will never be used.
2565 llvm::SmallVector<bool, 8> DeducibleParams;
2566 DeducibleParams.resize(TemplateParams->size());
2567 MarkDeducedTemplateParameters(Partial->getTemplateArgs(), DeducibleParams);
2568 unsigned NumNonDeducible = 0;
2569 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I)
2570 if (!DeducibleParams[I])
2571 ++NumNonDeducible;
2572
2573 if (NumNonDeducible) {
2574 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
2575 << (NumNonDeducible > 1)
2576 << SourceRange(TemplateNameLoc, RAngleLoc);
2577 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
2578 if (!DeducibleParams[I]) {
2579 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
2580 if (Param->getDeclName())
2581 Diag(Param->getLocation(),
2582 diag::note_partial_spec_unused_parameter)
2583 << Param->getDeclName();
2584 else
2585 Diag(Param->getLocation(),
2586 diag::note_partial_spec_unused_parameter)
2587 << std::string("<anonymous>");
2588 }
2589 }
2590 }
Douglas Gregorcc636682009-02-17 23:15:12 +00002591 } else {
2592 // Create a new class template specialization declaration node for
2593 // this explicit specialization.
2594 Specialization
2595 = ClassTemplateSpecializationDecl::Create(Context,
2596 ClassTemplate->getDeclContext(),
2597 TemplateNameLoc,
Anders Carlsson91fdf6f2009-06-05 04:06:48 +00002598 ClassTemplate,
Anders Carlssonfb250522009-06-23 01:26:57 +00002599 Converted,
Douglas Gregorcc636682009-02-17 23:15:12 +00002600 PrevDecl);
2601
2602 if (PrevDecl) {
2603 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
2604 ClassTemplate->getSpecializations().GetOrInsertNode(Specialization);
2605 } else {
2606 ClassTemplate->getSpecializations().InsertNode(Specialization,
2607 InsertPos);
2608 }
Douglas Gregorb88e8882009-07-30 17:40:51 +00002609
2610 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregorcc636682009-02-17 23:15:12 +00002611 }
2612
2613 // Note that this is an explicit specialization.
2614 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
2615
2616 // Check that this isn't a redefinition of this specialization.
John McCall0f434ec2009-07-31 02:45:11 +00002617 if (TUK == TUK_Definition) {
Douglas Gregorcc636682009-02-17 23:15:12 +00002618 if (RecordDecl *Def = Specialization->getDefinition(Context)) {
Mike Stump390b4cc2009-05-16 07:39:55 +00002619 // FIXME: Should also handle explicit specialization after implicit
2620 // instantiation with a special diagnostic.
Douglas Gregorcc636682009-02-17 23:15:12 +00002621 SourceRange Range(TemplateNameLoc, RAngleLoc);
2622 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002623 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregorcc636682009-02-17 23:15:12 +00002624 Diag(Def->getLocation(), diag::note_previous_definition);
2625 Specialization->setInvalidDecl();
Douglas Gregor212e81c2009-03-25 00:13:59 +00002626 return true;
Douglas Gregorcc636682009-02-17 23:15:12 +00002627 }
2628 }
2629
Douglas Gregorfc705b82009-02-26 22:19:44 +00002630 // Build the fully-sugared type for this class template
2631 // specialization as the user wrote in the specialization
2632 // itself. This means that we'll pretty-print the type retrieved
2633 // from the specialization's declaration the way that the user
2634 // actually wrote the specialization, rather than formatting the
2635 // name based on the "canonical" representation used to store the
2636 // template arguments in the specialization.
Douglas Gregore6258932009-03-19 00:39:20 +00002637 QualType WrittenTy
Douglas Gregor7532dc62009-03-30 22:58:21 +00002638 = Context.getTemplateSpecializationType(Name,
Anders Carlsson6360be72009-06-13 18:20:51 +00002639 TemplateArgs.data(),
Douglas Gregor7532dc62009-03-30 22:58:21 +00002640 TemplateArgs.size(),
Douglas Gregorb88e8882009-07-30 17:40:51 +00002641 CanonType);
Douglas Gregor7532dc62009-03-30 22:58:21 +00002642 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregor40808ce2009-03-09 23:48:35 +00002643 TemplateArgsIn.release();
Douglas Gregorcc636682009-02-17 23:15:12 +00002644
Douglas Gregor6bc9f7e2009-02-25 22:18:32 +00002645 // C++ [temp.expl.spec]p9:
2646 // A template explicit specialization is in the scope of the
2647 // namespace in which the template was defined.
2648 //
2649 // We actually implement this paragraph where we set the semantic
2650 // context (in the creation of the ClassTemplateSpecializationDecl),
2651 // but we also maintain the lexical context where the actual
2652 // definition occurs.
Douglas Gregorcc636682009-02-17 23:15:12 +00002653 Specialization->setLexicalDeclContext(CurContext);
2654
2655 // We may be starting the definition of this specialization.
John McCall0f434ec2009-07-31 02:45:11 +00002656 if (TUK == TUK_Definition)
Douglas Gregorcc636682009-02-17 23:15:12 +00002657 Specialization->startDefinition();
2658
2659 // Add the specialization into its lexical context, so that it can
2660 // be seen when iterating through the list of declarations in that
2661 // context. However, specializations are not found by name lookup.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002662 CurContext->addDecl(Specialization);
Chris Lattnerb28317a2009-03-28 19:18:32 +00002663 return DeclPtrTy::make(Specialization);
Douglas Gregorcc636682009-02-17 23:15:12 +00002664}
Douglas Gregord57959a2009-03-27 23:10:48 +00002665
Douglas Gregore542c862009-06-23 23:11:28 +00002666Sema::DeclPtrTy
2667Sema::ActOnTemplateDeclarator(Scope *S,
2668 MultiTemplateParamsArg TemplateParameterLists,
2669 Declarator &D) {
2670 return HandleDeclarator(S, D, move(TemplateParameterLists), false);
2671}
2672
Douglas Gregor52591bf2009-06-24 00:54:41 +00002673Sema::DeclPtrTy
2674Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
2675 MultiTemplateParamsArg TemplateParameterLists,
2676 Declarator &D) {
2677 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
2678 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
2679 "Not a function declarator!");
2680 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2681
2682 if (FTI.hasPrototype) {
2683 // FIXME: Diagnose arguments without names in C.
2684 }
2685
2686 Scope *ParentScope = FnBodyScope->getParent();
2687
2688 DeclPtrTy DP = HandleDeclarator(ParentScope, D,
2689 move(TemplateParameterLists),
2690 /*IsFunctionDefinition=*/true);
Douglas Gregorf59a56e2009-07-21 23:53:31 +00002691 if (FunctionTemplateDecl *FunctionTemplate
2692 = dyn_cast_or_null<FunctionTemplateDecl>(DP.getAs<Decl>()))
Douglas Gregore53060f2009-06-25 22:08:12 +00002693 return ActOnStartOfFunctionDef(FnBodyScope,
2694 DeclPtrTy::make(FunctionTemplate->getTemplatedDecl()));
Douglas Gregorf59a56e2009-07-21 23:53:31 +00002695 if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(DP.getAs<Decl>()))
2696 return ActOnStartOfFunctionDef(FnBodyScope, DeclPtrTy::make(Function));
Douglas Gregore53060f2009-06-25 22:08:12 +00002697 return DeclPtrTy();
Douglas Gregor52591bf2009-06-24 00:54:41 +00002698}
2699
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002700// Explicit instantiation of a class template specialization
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002701Sema::DeclResult
2702Sema::ActOnExplicitInstantiation(Scope *S, SourceLocation TemplateLoc,
2703 unsigned TagSpec,
2704 SourceLocation KWLoc,
2705 const CXXScopeSpec &SS,
2706 TemplateTy TemplateD,
2707 SourceLocation TemplateNameLoc,
2708 SourceLocation LAngleLoc,
2709 ASTTemplateArgsPtr TemplateArgsIn,
2710 SourceLocation *TemplateArgLocs,
2711 SourceLocation RAngleLoc,
2712 AttributeList *Attr) {
2713 // Find the class template we're specializing
2714 TemplateName Name = TemplateD.getAsVal<TemplateName>();
2715 ClassTemplateDecl *ClassTemplate
2716 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
2717
2718 // Check that the specialization uses the same tag kind as the
2719 // original template.
2720 TagDecl::TagKind Kind;
2721 switch (TagSpec) {
2722 default: assert(0 && "Unknown tag type!");
2723 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2724 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2725 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2726 }
Douglas Gregor501c5ce2009-05-14 16:41:31 +00002727 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
2728 Kind, KWLoc,
2729 *ClassTemplate->getIdentifier())) {
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002730 Diag(KWLoc, diag::err_use_with_wrong_tag)
2731 << ClassTemplate
2732 << CodeModificationHint::CreateReplacement(KWLoc,
2733 ClassTemplate->getTemplatedDecl()->getKindName());
2734 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
2735 diag::note_previous_use);
2736 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
2737 }
2738
Douglas Gregorff668032009-05-13 18:28:20 +00002739 // C++0x [temp.explicit]p2:
2740 // [...] An explicit instantiation shall appear in an enclosing
2741 // namespace of its template. [...]
2742 //
2743 // This is C++ DR 275.
2744 if (CheckClassTemplateSpecializationScope(ClassTemplate, 0,
2745 TemplateNameLoc,
2746 SS.getRange(),
Douglas Gregor16df8502009-06-12 22:21:45 +00002747 /*PartialSpecialization=*/false,
Douglas Gregorff668032009-05-13 18:28:20 +00002748 /*ExplicitInstantiation=*/true))
2749 return true;
2750
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002751 // Translate the parser's template argument list in our AST format.
2752 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
2753 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
2754
2755 // Check that the template argument list is well-formed for this
2756 // template.
Anders Carlssonfb250522009-06-23 01:26:57 +00002757 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
2758 TemplateArgs.size());
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002759 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
Anders Carlsson9bff9a92009-06-05 02:12:32 +00002760 TemplateArgs.data(), TemplateArgs.size(),
Douglas Gregor16134c62009-07-01 00:28:38 +00002761 RAngleLoc, false, Converted))
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002762 return true;
2763
Anders Carlssonfb250522009-06-23 01:26:57 +00002764 assert((Converted.structuredSize() ==
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002765 ClassTemplate->getTemplateParameters()->size()) &&
2766 "Converted template argument list is too short!");
2767
2768 // Find the class template specialization declaration that
2769 // corresponds to these arguments.
2770 llvm::FoldingSetNodeID ID;
Anders Carlsson1c5976e2009-06-05 03:43:12 +00002771 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlssonfb250522009-06-23 01:26:57 +00002772 Converted.getFlatArguments(),
Douglas Gregor828e2262009-07-29 16:09:57 +00002773 Converted.flatSize(),
2774 Context);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002775 void *InsertPos = 0;
2776 ClassTemplateSpecializationDecl *PrevDecl
2777 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
2778
2779 ClassTemplateSpecializationDecl *Specialization = 0;
2780
Douglas Gregorff668032009-05-13 18:28:20 +00002781 bool SpecializationRequiresInstantiation = true;
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002782 if (PrevDecl) {
Douglas Gregorff668032009-05-13 18:28:20 +00002783 if (PrevDecl->getSpecializationKind() == TSK_ExplicitInstantiation) {
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002784 // This particular specialization has already been declared or
2785 // instantiated. We cannot explicitly instantiate it.
Douglas Gregorff668032009-05-13 18:28:20 +00002786 Diag(TemplateNameLoc, diag::err_explicit_instantiation_duplicate)
2787 << Context.getTypeDeclType(PrevDecl);
2788 Diag(PrevDecl->getLocation(),
2789 diag::note_previous_explicit_instantiation);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002790 return DeclPtrTy::make(PrevDecl);
2791 }
2792
Douglas Gregorff668032009-05-13 18:28:20 +00002793 if (PrevDecl->getSpecializationKind() == TSK_ExplicitSpecialization) {
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002794 // C++ DR 259, C++0x [temp.explicit]p4:
Douglas Gregorff668032009-05-13 18:28:20 +00002795 // For a given set of template parameters, if an explicit
2796 // instantiation of a template appears after a declaration of
2797 // an explicit specialization for that template, the explicit
2798 // instantiation has no effect.
2799 if (!getLangOptions().CPlusPlus0x) {
2800 Diag(TemplateNameLoc,
2801 diag::ext_explicit_instantiation_after_specialization)
2802 << Context.getTypeDeclType(PrevDecl);
2803 Diag(PrevDecl->getLocation(),
2804 diag::note_previous_template_specialization);
2805 }
2806
2807 // Create a new class template specialization declaration node
2808 // for this explicit specialization. This node is only used to
2809 // record the existence of this explicit instantiation for
2810 // accurate reproduction of the source code; we don't actually
2811 // use it for anything, since it is semantically irrelevant.
2812 Specialization
2813 = ClassTemplateSpecializationDecl::Create(Context,
2814 ClassTemplate->getDeclContext(),
2815 TemplateNameLoc,
2816 ClassTemplate,
Anders Carlssonfb250522009-06-23 01:26:57 +00002817 Converted, 0);
Douglas Gregorff668032009-05-13 18:28:20 +00002818 Specialization->setLexicalDeclContext(CurContext);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002819 CurContext->addDecl(Specialization);
Douglas Gregorff668032009-05-13 18:28:20 +00002820 return DeclPtrTy::make(Specialization);
2821 }
2822
2823 // If we have already (implicitly) instantiated this
2824 // specialization, there is less work to do.
2825 if (PrevDecl->getSpecializationKind() == TSK_ImplicitInstantiation)
2826 SpecializationRequiresInstantiation = false;
2827
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002828 // Since the only prior class template specialization with these
2829 // arguments was referenced but not declared, reuse that
2830 // declaration node as our own, updating its source location to
2831 // reflect our new declaration.
2832 Specialization = PrevDecl;
2833 Specialization->setLocation(TemplateNameLoc);
2834 PrevDecl = 0;
2835 } else {
2836 // Create a new class template specialization declaration node for
2837 // this explicit specialization.
2838 Specialization
2839 = ClassTemplateSpecializationDecl::Create(Context,
2840 ClassTemplate->getDeclContext(),
2841 TemplateNameLoc,
2842 ClassTemplate,
Anders Carlssonfb250522009-06-23 01:26:57 +00002843 Converted, 0);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002844
2845 ClassTemplate->getSpecializations().InsertNode(Specialization,
2846 InsertPos);
2847 }
2848
2849 // Build the fully-sugared type for this explicit instantiation as
2850 // the user wrote in the explicit instantiation itself. This means
2851 // that we'll pretty-print the type retrieved from the
2852 // specialization's declaration the way that the user actually wrote
2853 // the explicit instantiation, rather than formatting the name based
2854 // on the "canonical" representation used to store the template
2855 // arguments in the specialization.
2856 QualType WrittenTy
2857 = Context.getTemplateSpecializationType(Name,
Anders Carlssonf4e2a2c2009-06-05 02:45:24 +00002858 TemplateArgs.data(),
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002859 TemplateArgs.size(),
2860 Context.getTypeDeclType(Specialization));
2861 Specialization->setTypeAsWritten(WrittenTy);
2862 TemplateArgsIn.release();
2863
2864 // Add the explicit instantiation into its lexical context. However,
2865 // since explicit instantiations are never found by name lookup, we
2866 // just put it into the declaration context directly.
2867 Specialization->setLexicalDeclContext(CurContext);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002868 CurContext->addDecl(Specialization);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002869
2870 // C++ [temp.explicit]p3:
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002871 // A definition of a class template or class member template
2872 // shall be in scope at the point of the explicit instantiation of
2873 // the class template or class member template.
2874 //
2875 // This check comes when we actually try to perform the
2876 // instantiation.
Douglas Gregore2c31ff2009-05-15 17:59:04 +00002877 if (SpecializationRequiresInstantiation)
2878 InstantiateClassTemplateSpecialization(Specialization, true);
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00002879 else // Instantiate the members of this class template specialization.
Douglas Gregore2c31ff2009-05-15 17:59:04 +00002880 InstantiateClassTemplateSpecializationMembers(TemplateLoc, Specialization);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002881
2882 return DeclPtrTy::make(Specialization);
2883}
2884
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002885// Explicit instantiation of a member class of a class template.
2886Sema::DeclResult
2887Sema::ActOnExplicitInstantiation(Scope *S, SourceLocation TemplateLoc,
2888 unsigned TagSpec,
2889 SourceLocation KWLoc,
2890 const CXXScopeSpec &SS,
2891 IdentifierInfo *Name,
2892 SourceLocation NameLoc,
2893 AttributeList *Attr) {
2894
Douglas Gregor402abb52009-05-28 23:31:59 +00002895 bool Owned = false;
John McCall0f434ec2009-07-31 02:45:11 +00002896 DeclPtrTy TagD = ActOnTag(S, TagSpec, Action::TUK_Reference,
Douglas Gregor7cdbc582009-07-22 23:48:44 +00002897 KWLoc, SS, Name, NameLoc, Attr, AS_none,
2898 MultiTemplateParamsArg(*this, 0, 0), Owned);
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002899 if (!TagD)
2900 return true;
2901
2902 TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
2903 if (Tag->isEnum()) {
2904 Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
2905 << Context.getTypeDeclType(Tag);
2906 return true;
2907 }
2908
Douglas Gregord0c87372009-05-27 17:30:49 +00002909 if (Tag->isInvalidDecl())
2910 return true;
2911
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002912 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
2913 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
2914 if (!Pattern) {
2915 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
2916 << Context.getTypeDeclType(Record);
2917 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
2918 return true;
2919 }
2920
2921 // C++0x [temp.explicit]p2:
2922 // [...] An explicit instantiation shall appear in an enclosing
2923 // namespace of its template. [...]
2924 //
2925 // This is C++ DR 275.
2926 if (getLangOptions().CPlusPlus0x) {
Mike Stump390b4cc2009-05-16 07:39:55 +00002927 // FIXME: In C++98, we would like to turn these errors into warnings,
2928 // dependent on a -Wc++0x flag.
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002929 DeclContext *PatternContext
2930 = Pattern->getDeclContext()->getEnclosingNamespaceContext();
2931 if (!CurContext->Encloses(PatternContext)) {
2932 Diag(TemplateLoc, diag::err_explicit_instantiation_out_of_scope)
2933 << Record << cast<NamedDecl>(PatternContext) << SS.getRange();
2934 Diag(Pattern->getLocation(), diag::note_previous_declaration);
2935 }
2936 }
2937
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002938 if (!Record->getDefinition(Context)) {
2939 // If the class has a definition, instantiate it (and all of its
2940 // members, recursively).
2941 Pattern = cast_or_null<CXXRecordDecl>(Pattern->getDefinition(Context));
2942 if (Pattern && InstantiateClass(TemplateLoc, Record, Pattern,
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002943 getTemplateInstantiationArgs(Record),
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002944 /*ExplicitInstantiation=*/true))
2945 return true;
John McCallce3ff2b2009-08-25 22:02:44 +00002946 } else // Instantiate all of the members of the class.
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002947 InstantiateClassMembers(TemplateLoc, Record,
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002948 getTemplateInstantiationArgs(Record));
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002949
Mike Stump390b4cc2009-05-16 07:39:55 +00002950 // FIXME: We don't have any representation for explicit instantiations of
2951 // member classes. Such a representation is not needed for compilation, but it
2952 // should be available for clients that want to see all of the declarations in
2953 // the source code.
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002954 return TagD;
2955}
2956
Douglas Gregord57959a2009-03-27 23:10:48 +00002957Sema::TypeResult
2958Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
2959 const IdentifierInfo &II, SourceLocation IdLoc) {
2960 NestedNameSpecifier *NNS
2961 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
2962 if (!NNS)
2963 return true;
2964
2965 QualType T = CheckTypenameType(NNS, II, SourceRange(TypenameLoc, IdLoc));
Douglas Gregor31a19b62009-04-01 21:51:26 +00002966 if (T.isNull())
2967 return true;
Douglas Gregord57959a2009-03-27 23:10:48 +00002968 return T.getAsOpaquePtr();
2969}
2970
Douglas Gregor17343172009-04-01 00:28:59 +00002971Sema::TypeResult
2972Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
2973 SourceLocation TemplateLoc, TypeTy *Ty) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00002974 QualType T = GetTypeFromParser(Ty);
Douglas Gregor17343172009-04-01 00:28:59 +00002975 NestedNameSpecifier *NNS
2976 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
2977 const TemplateSpecializationType *TemplateId
2978 = T->getAsTemplateSpecializationType();
2979 assert(TemplateId && "Expected a template specialization type");
2980
2981 if (NNS->isDependent())
2982 return Context.getTypenameType(NNS, TemplateId).getAsOpaquePtr();
2983
2984 return Context.getQualifiedNameType(NNS, T).getAsOpaquePtr();
2985}
2986
Douglas Gregord57959a2009-03-27 23:10:48 +00002987/// \brief Build the type that describes a C++ typename specifier,
2988/// e.g., "typename T::type".
2989QualType
2990Sema::CheckTypenameType(NestedNameSpecifier *NNS, const IdentifierInfo &II,
2991 SourceRange Range) {
Douglas Gregor42af25f2009-05-11 19:58:34 +00002992 CXXRecordDecl *CurrentInstantiation = 0;
2993 if (NNS->isDependent()) {
2994 CurrentInstantiation = getCurrentInstantiationOf(NNS);
Douglas Gregord57959a2009-03-27 23:10:48 +00002995
Douglas Gregor42af25f2009-05-11 19:58:34 +00002996 // If the nested-name-specifier does not refer to the current
2997 // instantiation, then build a typename type.
2998 if (!CurrentInstantiation)
2999 return Context.getTypenameType(NNS, &II);
3000 }
Douglas Gregord57959a2009-03-27 23:10:48 +00003001
Douglas Gregor42af25f2009-05-11 19:58:34 +00003002 DeclContext *Ctx = 0;
3003
3004 if (CurrentInstantiation)
3005 Ctx = CurrentInstantiation;
3006 else {
3007 CXXScopeSpec SS;
3008 SS.setScopeRep(NNS);
3009 SS.setRange(Range);
3010 if (RequireCompleteDeclContext(SS))
3011 return QualType();
3012
3013 Ctx = computeDeclContext(SS);
3014 }
Douglas Gregord57959a2009-03-27 23:10:48 +00003015 assert(Ctx && "No declaration context?");
3016
3017 DeclarationName Name(&II);
3018 LookupResult Result = LookupQualifiedName(Ctx, Name, LookupOrdinaryName,
3019 false);
3020 unsigned DiagID = 0;
3021 Decl *Referenced = 0;
3022 switch (Result.getKind()) {
3023 case LookupResult::NotFound:
3024 if (Ctx->isTranslationUnit())
3025 DiagID = diag::err_typename_nested_not_found_global;
3026 else
3027 DiagID = diag::err_typename_nested_not_found;
3028 break;
3029
3030 case LookupResult::Found:
3031 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getAsDecl())) {
3032 // We found a type. Build a QualifiedNameType, since the
3033 // typename-specifier was just sugar. FIXME: Tell
3034 // QualifiedNameType that it has a "typename" prefix.
3035 return Context.getQualifiedNameType(NNS, Context.getTypeDeclType(Type));
3036 }
3037
3038 DiagID = diag::err_typename_nested_not_type;
3039 Referenced = Result.getAsDecl();
3040 break;
3041
3042 case LookupResult::FoundOverloaded:
3043 DiagID = diag::err_typename_nested_not_type;
3044 Referenced = *Result.begin();
3045 break;
3046
3047 case LookupResult::AmbiguousBaseSubobjectTypes:
3048 case LookupResult::AmbiguousBaseSubobjects:
3049 case LookupResult::AmbiguousReference:
3050 DiagnoseAmbiguousLookup(Result, Name, Range.getEnd(), Range);
3051 return QualType();
3052 }
3053
3054 // If we get here, it's because name lookup did not find a
3055 // type. Emit an appropriate diagnostic and return an error.
3056 if (NamedDecl *NamedCtx = dyn_cast<NamedDecl>(Ctx))
3057 Diag(Range.getEnd(), DiagID) << Range << Name << NamedCtx;
3058 else
3059 Diag(Range.getEnd(), DiagID) << Range << Name;
3060 if (Referenced)
3061 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
3062 << Name;
3063 return QualType();
3064}
Douglas Gregor4a959d82009-08-06 16:20:37 +00003065
3066namespace {
3067 // See Sema::RebuildTypeInCurrentInstantiation
3068 class VISIBILITY_HIDDEN CurrentInstantiationRebuilder
3069 : public TreeTransform<CurrentInstantiationRebuilder>
3070 {
3071 SourceLocation Loc;
3072 DeclarationName Entity;
3073
3074 public:
3075 CurrentInstantiationRebuilder(Sema &SemaRef,
3076 SourceLocation Loc,
3077 DeclarationName Entity)
3078 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
3079 Loc(Loc), Entity(Entity) { }
3080
3081 /// \brief Determine whether the given type \p T has already been
3082 /// transformed.
3083 ///
3084 /// For the purposes of type reconstruction, a type has already been
3085 /// transformed if it is NULL or if it is not dependent.
3086 bool AlreadyTransformed(QualType T) {
3087 return T.isNull() || !T->isDependentType();
3088 }
3089
3090 /// \brief Returns the location of the entity whose type is being
3091 /// rebuilt.
3092 SourceLocation getBaseLocation() { return Loc; }
3093
3094 /// \brief Returns the name of the entity whose type is being rebuilt.
3095 DeclarationName getBaseEntity() { return Entity; }
3096
3097 /// \brief Transforms an expression by returning the expression itself
3098 /// (an identity function).
3099 ///
3100 /// FIXME: This is completely unsafe; we will need to actually clone the
3101 /// expressions.
3102 Sema::OwningExprResult TransformExpr(Expr *E) {
3103 return getSema().Owned(E);
3104 }
3105
3106 /// \brief Transforms a typename type by determining whether the type now
3107 /// refers to a member of the current instantiation, and then
3108 /// type-checking and building a QualifiedNameType (when possible).
3109 QualType TransformTypenameType(const TypenameType *T);
3110 };
3111}
3112
3113QualType
3114CurrentInstantiationRebuilder::TransformTypenameType(const TypenameType *T) {
3115 NestedNameSpecifier *NNS
3116 = TransformNestedNameSpecifier(T->getQualifier(),
3117 /*FIXME:*/SourceRange(getBaseLocation()));
3118 if (!NNS)
3119 return QualType();
3120
3121 // If the nested-name-specifier did not change, and we cannot compute the
3122 // context corresponding to the nested-name-specifier, then this
3123 // typename type will not change; exit early.
3124 CXXScopeSpec SS;
3125 SS.setRange(SourceRange(getBaseLocation()));
3126 SS.setScopeRep(NNS);
3127 if (NNS == T->getQualifier() && getSema().computeDeclContext(SS) == 0)
3128 return QualType(T, 0);
3129
3130 // Rebuild the typename type, which will probably turn into a
3131 // QualifiedNameType.
3132 if (const TemplateSpecializationType *TemplateId = T->getTemplateId()) {
3133 QualType NewTemplateId
3134 = TransformType(QualType(TemplateId, 0));
3135 if (NewTemplateId.isNull())
3136 return QualType();
3137
3138 if (NNS == T->getQualifier() &&
3139 NewTemplateId == QualType(TemplateId, 0))
3140 return QualType(T, 0);
3141
3142 return getDerived().RebuildTypenameType(NNS, NewTemplateId);
3143 }
3144
3145 return getDerived().RebuildTypenameType(NNS, T->getIdentifier());
3146}
3147
3148/// \brief Rebuilds a type within the context of the current instantiation.
3149///
3150/// The type \p T is part of the type of an out-of-line member definition of
3151/// a class template (or class template partial specialization) that was parsed
3152/// and constructed before we entered the scope of the class template (or
3153/// partial specialization thereof). This routine will rebuild that type now
3154/// that we have entered the declarator's scope, which may produce different
3155/// canonical types, e.g.,
3156///
3157/// \code
3158/// template<typename T>
3159/// struct X {
3160/// typedef T* pointer;
3161/// pointer data();
3162/// };
3163///
3164/// template<typename T>
3165/// typename X<T>::pointer X<T>::data() { ... }
3166/// \endcode
3167///
3168/// Here, the type "typename X<T>::pointer" will be created as a TypenameType,
3169/// since we do not know that we can look into X<T> when we parsed the type.
3170/// This function will rebuild the type, performing the lookup of "pointer"
3171/// in X<T> and returning a QualifiedNameType whose canonical type is the same
3172/// as the canonical type of T*, allowing the return types of the out-of-line
3173/// definition and the declaration to match.
3174QualType Sema::RebuildTypeInCurrentInstantiation(QualType T, SourceLocation Loc,
3175 DeclarationName Name) {
3176 if (T.isNull() || !T->isDependentType())
3177 return T;
3178
3179 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
3180 return Rebuilder.TransformType(T);
Benjamin Kramer27ba2f02009-08-11 22:33:06 +00003181}