blob: 56a016d2703b929861d53628be63a90057f84adc [file] [log] [blame]
Douglas Gregordd861062008-12-05 18:15:24 +00001//===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===/
2
3//
4// The LLVM Compiler Infrastructure
5//
6// This file is distributed under the University of Illinois Open Source
7// License. See LICENSE.TXT for details.
Douglas Gregor74296542009-02-27 19:31:52 +00008//===----------------------------------------------------------------------===/
Douglas Gregordd861062008-12-05 18:15:24 +00009
10//
11// This file implements semantic analysis for C++ templates.
Douglas Gregor74296542009-02-27 19:31:52 +000012//===----------------------------------------------------------------------===/
Douglas Gregordd861062008-12-05 18:15:24 +000013
14#include "Sema.h"
Douglas Gregord406b032009-02-06 22:42:48 +000015#include "clang/AST/ASTContext.h"
Douglas Gregor1b21c7f2008-12-05 23:32:09 +000016#include "clang/AST/Expr.h"
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +000017#include "clang/AST/ExprCXX.h"
Douglas Gregor279272e2009-02-04 19:02:06 +000018#include "clang/AST/DeclTemplate.h"
Douglas Gregordd861062008-12-05 18:15:24 +000019#include "clang/Parse/DeclSpec.h"
20#include "clang/Basic/LangOptions.h"
21
22using namespace clang;
23
Douglas Gregor2fa10442008-12-18 19:37:40 +000024/// isTemplateName - Determines whether the identifier II is a
25/// template name in the current scope, and returns the template
26/// declaration if II names a template. An optional CXXScope can be
27/// passed to indicate the C++ scope in which the identifier will be
28/// found.
Douglas Gregor0c281a82009-02-25 19:37:18 +000029TemplateNameKind Sema::isTemplateName(IdentifierInfo &II, Scope *S,
Douglas Gregordd13e842009-03-30 22:58:21 +000030 TemplateTy &TemplateResult,
Douglas Gregor0c281a82009-02-25 19:37:18 +000031 const CXXScopeSpec *SS) {
Douglas Gregor09be81b2009-02-04 17:27:36 +000032 NamedDecl *IIDecl = LookupParsedName(S, SS, &II, LookupOrdinaryName);
Douglas Gregor2fa10442008-12-18 19:37:40 +000033
Douglas Gregordd13e842009-03-30 22:58:21 +000034 TemplateNameKind TNK = TNK_Non_template;
35 TemplateDecl *Template = 0;
36
Douglas Gregor2fa10442008-12-18 19:37:40 +000037 if (IIDecl) {
Douglas Gregordd13e842009-03-30 22:58:21 +000038 if ((Template = dyn_cast<TemplateDecl>(IIDecl))) {
Douglas Gregor8e458f42009-02-09 18:46:07 +000039 if (isa<FunctionTemplateDecl>(IIDecl))
Douglas Gregordd13e842009-03-30 22:58:21 +000040 TNK = TNK_Function_template;
41 else if (isa<ClassTemplateDecl>(IIDecl))
42 TNK = TNK_Class_template;
43 else if (isa<TemplateTemplateParmDecl>(IIDecl))
44 TNK = TNK_Template_template_parm;
45 else
46 assert(false && "Unknown template declaration kind");
Douglas Gregor55216ac2009-03-26 00:10:35 +000047 } else if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(IIDecl)) {
48 // C++ [temp.local]p1:
49 // Like normal (non-template) classes, class templates have an
50 // injected-class-name (Clause 9). The injected-class-name
51 // can be used with or without a template-argument-list. When
52 // it is used without a template-argument-list, it is
53 // equivalent to the injected-class-name followed by the
54 // template-parameters of the class template enclosed in
55 // <>. When it is used with a template-argument-list, it
56 // refers to the specified class template specialization,
57 // which could be the current specialization or another
58 // specialization.
59 if (Record->isInjectedClassName()) {
60 Record = cast<CXXRecordDecl>(Context.getCanonicalDecl(Record));
Douglas Gregordd13e842009-03-30 22:58:21 +000061 if ((Template = Record->getDescribedClassTemplate()))
62 TNK = TNK_Class_template;
63 else if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor55216ac2009-03-26 00:10:35 +000064 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
Douglas Gregordd13e842009-03-30 22:58:21 +000065 Template = Spec->getSpecializedTemplate();
66 TNK = TNK_Class_template;
Douglas Gregor55216ac2009-03-26 00:10:35 +000067 }
68 }
Douglas Gregor8e458f42009-02-09 18:46:07 +000069 }
Douglas Gregor279272e2009-02-04 19:02:06 +000070
Douglas Gregor8e458f42009-02-09 18:46:07 +000071 // FIXME: What follows is a gross hack.
Douglas Gregor2fa10442008-12-18 19:37:40 +000072 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(IIDecl)) {
Douglas Gregor8e458f42009-02-09 18:46:07 +000073 if (FD->getType()->isDependentType()) {
Douglas Gregordd13e842009-03-30 22:58:21 +000074 TemplateResult = TemplateTy::make(FD);
Douglas Gregor8e458f42009-02-09 18:46:07 +000075 return TNK_Function_template;
76 }
Douglas Gregor2fa10442008-12-18 19:37:40 +000077 } else if (OverloadedFunctionDecl *Ovl
78 = dyn_cast<OverloadedFunctionDecl>(IIDecl)) {
79 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
80 FEnd = Ovl->function_end();
81 F != FEnd; ++F) {
Douglas Gregor8e458f42009-02-09 18:46:07 +000082 if ((*F)->getType()->isDependentType()) {
Douglas Gregordd13e842009-03-30 22:58:21 +000083 TemplateResult = TemplateTy::make(Ovl);
Douglas Gregor8e458f42009-02-09 18:46:07 +000084 return TNK_Function_template;
85 }
Douglas Gregor2fa10442008-12-18 19:37:40 +000086 }
87 }
Douglas Gregordd13e842009-03-30 22:58:21 +000088
89 if (TNK != TNK_Non_template) {
90 if (SS && SS->isSet() && !SS->isInvalid()) {
91 NestedNameSpecifier *Qualifier
92 = static_cast<NestedNameSpecifier *>(SS->getScopeRep());
93 TemplateResult
94 = TemplateTy::make(Context.getQualifiedTemplateName(Qualifier,
95 false,
96 Template));
97 } else
98 TemplateResult = TemplateTy::make(TemplateName(Template));
99 }
Douglas Gregor2fa10442008-12-18 19:37:40 +0000100 }
Douglas Gregordd13e842009-03-30 22:58:21 +0000101 return TNK;
Douglas Gregor2fa10442008-12-18 19:37:40 +0000102}
103
Douglas Gregordd861062008-12-05 18:15:24 +0000104/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
105/// that the template parameter 'PrevDecl' is being shadowed by a new
106/// declaration at location Loc. Returns true to indicate that this is
107/// an error, and false otherwise.
108bool Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
Douglas Gregor2715a1f2008-12-08 18:40:42 +0000109 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregordd861062008-12-05 18:15:24 +0000110
111 // Microsoft Visual C++ permits template parameters to be shadowed.
112 if (getLangOptions().Microsoft)
113 return false;
114
115 // C++ [temp.local]p4:
116 // A template-parameter shall not be redeclared within its
117 // scope (including nested scopes).
118 Diag(Loc, diag::err_template_param_shadow)
119 << cast<NamedDecl>(PrevDecl)->getDeclName();
120 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
121 return true;
122}
123
Douglas Gregored3a3982009-03-03 04:44:36 +0000124/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregor279272e2009-02-04 19:02:06 +0000125/// the parameter D to reference the templated declaration and return a pointer
126/// to the template declaration. Otherwise, do nothing to D and return null.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000127TemplateDecl *Sema::AdjustDeclIfTemplate(DeclPtrTy &D) {
128 if (TemplateDecl *Temp = dyn_cast<TemplateDecl>(D.getAs<Decl>())) {
129 D = DeclPtrTy::make(Temp->getTemplatedDecl());
Douglas Gregor279272e2009-02-04 19:02:06 +0000130 return Temp;
131 }
132 return 0;
133}
134
Douglas Gregordd861062008-12-05 18:15:24 +0000135/// ActOnTypeParameter - Called when a C++ template type parameter
136/// (e.g., "typename T") has been parsed. Typename specifies whether
137/// the keyword "typename" was used to declare the type parameter
138/// (otherwise, "class" was used), and KeyLoc is the location of the
139/// "class" or "typename" keyword. ParamName is the name of the
140/// parameter (NULL indicates an unnamed template parameter) and
141/// ParamName is the location of the parameter name (if any).
142/// If the type parameter has a default argument, it will be added
143/// later via ActOnTypeParameterDefault.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000144Sema::DeclPtrTy Sema::ActOnTypeParameter(Scope *S, bool Typename,
145 SourceLocation KeyLoc,
146 IdentifierInfo *ParamName,
147 SourceLocation ParamNameLoc,
148 unsigned Depth, unsigned Position) {
Douglas Gregordd861062008-12-05 18:15:24 +0000149 assert(S->isTemplateParamScope() &&
150 "Template type parameter not in template parameter scope!");
151 bool Invalid = false;
152
153 if (ParamName) {
Douglas Gregor09be81b2009-02-04 17:27:36 +0000154 NamedDecl *PrevDecl = LookupName(S, ParamName, LookupTagName);
Douglas Gregor2715a1f2008-12-08 18:40:42 +0000155 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregordd861062008-12-05 18:15:24 +0000156 Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc,
157 PrevDecl);
158 }
159
Douglas Gregord406b032009-02-06 22:42:48 +0000160 SourceLocation Loc = ParamNameLoc;
161 if (!ParamName)
162 Loc = KeyLoc;
163
Douglas Gregordd861062008-12-05 18:15:24 +0000164 TemplateTypeParmDecl *Param
Douglas Gregord406b032009-02-06 22:42:48 +0000165 = TemplateTypeParmDecl::Create(Context, CurContext, Loc,
Douglas Gregor279272e2009-02-04 19:02:06 +0000166 Depth, Position, ParamName, Typename);
Douglas Gregordd861062008-12-05 18:15:24 +0000167 if (Invalid)
168 Param->setInvalidDecl();
169
170 if (ParamName) {
171 // Add the template parameter into the current scope.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000172 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregordd861062008-12-05 18:15:24 +0000173 IdResolver.AddDecl(Param);
174 }
175
Chris Lattner5261d0c2009-03-28 19:18:32 +0000176 return DeclPtrTy::make(Param);
Douglas Gregordd861062008-12-05 18:15:24 +0000177}
178
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000179/// ActOnTypeParameterDefault - Adds a default argument (the type
180/// Default) to the given template type parameter (TypeParam).
Chris Lattner5261d0c2009-03-28 19:18:32 +0000181void Sema::ActOnTypeParameterDefault(DeclPtrTy TypeParam,
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000182 SourceLocation EqualLoc,
183 SourceLocation DefaultLoc,
184 TypeTy *DefaultT) {
185 TemplateTypeParmDecl *Parm
Chris Lattner5261d0c2009-03-28 19:18:32 +0000186 = cast<TemplateTypeParmDecl>(TypeParam.getAs<Decl>());
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000187 QualType Default = QualType::getFromOpaquePtr(DefaultT);
188
189 // C++ [temp.param]p14:
190 // A template-parameter shall not be used in its own default argument.
191 // FIXME: Implement this check! Needs a recursive walk over the types.
192
193 // Check the template argument itself.
194 if (CheckTemplateArgument(Parm, Default, DefaultLoc)) {
195 Parm->setInvalidDecl();
196 return;
197 }
198
199 Parm->setDefaultArgument(Default, DefaultLoc, false);
200}
201
Douglas Gregored3a3982009-03-03 04:44:36 +0000202/// \brief Check that the type of a non-type template parameter is
203/// well-formed.
204///
205/// \returns the (possibly-promoted) parameter type if valid;
206/// otherwise, produces a diagnostic and returns a NULL type.
207QualType
208Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
209 // C++ [temp.param]p4:
210 //
211 // A non-type template-parameter shall have one of the following
212 // (optionally cv-qualified) types:
213 //
214 // -- integral or enumeration type,
215 if (T->isIntegralType() || T->isEnumeralType() ||
216 // -- pointer to object or pointer to function,
217 (T->isPointerType() &&
218 (T->getAsPointerType()->getPointeeType()->isObjectType() ||
219 T->getAsPointerType()->getPointeeType()->isFunctionType())) ||
220 // -- reference to object or reference to function,
221 T->isReferenceType() ||
222 // -- pointer to member.
223 T->isMemberPointerType() ||
224 // If T is a dependent type, we can't do the check now, so we
225 // assume that it is well-formed.
226 T->isDependentType())
227 return T;
228 // C++ [temp.param]p8:
229 //
230 // A non-type template-parameter of type "array of T" or
231 // "function returning T" is adjusted to be of type "pointer to
232 // T" or "pointer to function returning T", respectively.
233 else if (T->isArrayType())
234 // FIXME: Keep the type prior to promotion?
235 return Context.getArrayDecayedType(T);
236 else if (T->isFunctionType())
237 // FIXME: Keep the type prior to promotion?
238 return Context.getPointerType(T);
239
240 Diag(Loc, diag::err_template_nontype_parm_bad_type)
241 << T;
242
243 return QualType();
244}
245
Douglas Gregordd861062008-12-05 18:15:24 +0000246/// ActOnNonTypeTemplateParameter - Called when a C++ non-type
247/// template parameter (e.g., "int Size" in "template<int Size>
248/// class Array") has been parsed. S is the current scope and D is
249/// the parsed declarator.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000250Sema::DeclPtrTy Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
251 unsigned Depth,
252 unsigned Position) {
Douglas Gregordd861062008-12-05 18:15:24 +0000253 QualType T = GetTypeForDeclarator(D, S);
254
Douglas Gregor279272e2009-02-04 19:02:06 +0000255 assert(S->isTemplateParamScope() &&
256 "Non-type template parameter not in template parameter scope!");
Douglas Gregordd861062008-12-05 18:15:24 +0000257 bool Invalid = false;
258
259 IdentifierInfo *ParamName = D.getIdentifier();
260 if (ParamName) {
Douglas Gregor09be81b2009-02-04 17:27:36 +0000261 NamedDecl *PrevDecl = LookupName(S, ParamName, LookupTagName);
Douglas Gregor2715a1f2008-12-08 18:40:42 +0000262 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregordd861062008-12-05 18:15:24 +0000263 Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
Douglas Gregor279272e2009-02-04 19:02:06 +0000264 PrevDecl);
Douglas Gregordd861062008-12-05 18:15:24 +0000265 }
266
Douglas Gregored3a3982009-03-03 04:44:36 +0000267 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
Douglas Gregor8b90e8e2009-03-09 16:46:39 +0000268 if (T.isNull()) {
Douglas Gregored3a3982009-03-03 04:44:36 +0000269 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregor8b90e8e2009-03-09 16:46:39 +0000270 Invalid = true;
271 }
Douglas Gregor62cdc792009-02-10 17:43:50 +0000272
Douglas Gregordd861062008-12-05 18:15:24 +0000273 NonTypeTemplateParmDecl *Param
274 = NonTypeTemplateParmDecl::Create(Context, CurContext, D.getIdentifierLoc(),
Douglas Gregor279272e2009-02-04 19:02:06 +0000275 Depth, Position, ParamName, T);
Douglas Gregordd861062008-12-05 18:15:24 +0000276 if (Invalid)
277 Param->setInvalidDecl();
278
279 if (D.getIdentifier()) {
280 // Add the template parameter into the current scope.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000281 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregordd861062008-12-05 18:15:24 +0000282 IdResolver.AddDecl(Param);
283 }
Chris Lattner5261d0c2009-03-28 19:18:32 +0000284 return DeclPtrTy::make(Param);
Douglas Gregordd861062008-12-05 18:15:24 +0000285}
Douglas Gregor52473432008-12-24 02:52:09 +0000286
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000287/// \brief Adds a default argument to the given non-type template
288/// parameter.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000289void Sema::ActOnNonTypeTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000290 SourceLocation EqualLoc,
291 ExprArg DefaultE) {
292 NonTypeTemplateParmDecl *TemplateParm
Chris Lattner5261d0c2009-03-28 19:18:32 +0000293 = cast<NonTypeTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000294 Expr *Default = static_cast<Expr *>(DefaultE.get());
295
296 // C++ [temp.param]p14:
297 // A template-parameter shall not be used in its own default argument.
298 // FIXME: Implement this check! Needs a recursive walk over the types.
299
300 // Check the well-formedness of the default template argument.
Douglas Gregored3a3982009-03-03 04:44:36 +0000301 if (CheckTemplateArgument(TemplateParm, TemplateParm->getType(), Default)) {
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000302 TemplateParm->setInvalidDecl();
303 return;
304 }
305
306 TemplateParm->setDefaultArgument(static_cast<Expr *>(DefaultE.release()));
307}
308
Douglas Gregor279272e2009-02-04 19:02:06 +0000309
310/// ActOnTemplateTemplateParameter - Called when a C++ template template
311/// parameter (e.g. T in template <template <typename> class T> class array)
312/// has been parsed. S is the current scope.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000313Sema::DeclPtrTy Sema::ActOnTemplateTemplateParameter(Scope* S,
314 SourceLocation TmpLoc,
315 TemplateParamsTy *Params,
316 IdentifierInfo *Name,
317 SourceLocation NameLoc,
318 unsigned Depth,
319 unsigned Position)
Douglas Gregor279272e2009-02-04 19:02:06 +0000320{
321 assert(S->isTemplateParamScope() &&
322 "Template template parameter not in template parameter scope!");
323
324 // Construct the parameter object.
325 TemplateTemplateParmDecl *Param =
326 TemplateTemplateParmDecl::Create(Context, CurContext, TmpLoc, Depth,
327 Position, Name,
328 (TemplateParameterList*)Params);
329
330 // Make sure the parameter is valid.
331 // FIXME: Decl object is not currently invalidated anywhere so this doesn't
332 // do anything yet. However, if the template parameter list or (eventual)
333 // default value is ever invalidated, that will propagate here.
334 bool Invalid = false;
335 if (Invalid) {
336 Param->setInvalidDecl();
337 }
338
339 // If the tt-param has a name, then link the identifier into the scope
340 // and lookup mechanisms.
341 if (Name) {
Chris Lattner5261d0c2009-03-28 19:18:32 +0000342 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor279272e2009-02-04 19:02:06 +0000343 IdResolver.AddDecl(Param);
344 }
345
Chris Lattner5261d0c2009-03-28 19:18:32 +0000346 return DeclPtrTy::make(Param);
Douglas Gregor279272e2009-02-04 19:02:06 +0000347}
348
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000349/// \brief Adds a default argument to the given template template
350/// parameter.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000351void Sema::ActOnTemplateTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000352 SourceLocation EqualLoc,
353 ExprArg DefaultE) {
354 TemplateTemplateParmDecl *TemplateParm
Chris Lattner5261d0c2009-03-28 19:18:32 +0000355 = cast<TemplateTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000356
357 // Since a template-template parameter's default argument is an
358 // id-expression, it must be a DeclRefExpr.
359 DeclRefExpr *Default
360 = cast<DeclRefExpr>(static_cast<Expr *>(DefaultE.get()));
361
362 // C++ [temp.param]p14:
363 // A template-parameter shall not be used in its own default argument.
364 // FIXME: Implement this check! Needs a recursive walk over the types.
365
366 // Check the well-formedness of the template argument.
367 if (!isa<TemplateDecl>(Default->getDecl())) {
368 Diag(Default->getSourceRange().getBegin(),
369 diag::err_template_arg_must_be_template)
370 << Default->getSourceRange();
371 TemplateParm->setInvalidDecl();
372 return;
373 }
374 if (CheckTemplateArgument(TemplateParm, Default)) {
375 TemplateParm->setInvalidDecl();
376 return;
377 }
378
379 DefaultE.release();
380 TemplateParm->setDefaultArgument(Default);
381}
382
Douglas Gregor52473432008-12-24 02:52:09 +0000383/// ActOnTemplateParameterList - Builds a TemplateParameterList that
384/// contains the template parameters in Params/NumParams.
385Sema::TemplateParamsTy *
386Sema::ActOnTemplateParameterList(unsigned Depth,
387 SourceLocation ExportLoc,
388 SourceLocation TemplateLoc,
389 SourceLocation LAngleLoc,
Chris Lattner5261d0c2009-03-28 19:18:32 +0000390 DeclPtrTy *Params, unsigned NumParams,
Douglas Gregor52473432008-12-24 02:52:09 +0000391 SourceLocation RAngleLoc) {
392 if (ExportLoc.isValid())
393 Diag(ExportLoc, diag::note_template_export_unsupported);
394
Douglas Gregord406b032009-02-06 22:42:48 +0000395 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
396 (Decl**)Params, NumParams, RAngleLoc);
Douglas Gregor52473432008-12-24 02:52:09 +0000397}
Douglas Gregor279272e2009-02-04 19:02:06 +0000398
Douglas Gregorc5d6fa72009-03-25 00:13:59 +0000399Sema::DeclResult
Douglas Gregord406b032009-02-06 22:42:48 +0000400Sema::ActOnClassTemplate(Scope *S, unsigned TagSpec, TagKind TK,
401 SourceLocation KWLoc, const CXXScopeSpec &SS,
402 IdentifierInfo *Name, SourceLocation NameLoc,
403 AttributeList *Attr,
Anders Carlssoned20fb92009-03-26 00:52:18 +0000404 MultiTemplateParamsArg TemplateParameterLists,
405 AccessSpecifier AS) {
Douglas Gregord406b032009-02-06 22:42:48 +0000406 assert(TemplateParameterLists.size() > 0 && "No template parameter lists?");
407 assert(TK != TK_Reference && "Can only declare or define class templates");
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000408 bool Invalid = false;
Douglas Gregord406b032009-02-06 22:42:48 +0000409
410 // Check that we can declare a template here.
411 if (CheckTemplateDeclScope(S, TemplateParameterLists))
Douglas Gregorc5d6fa72009-03-25 00:13:59 +0000412 return true;
Douglas Gregord406b032009-02-06 22:42:48 +0000413
414 TagDecl::TagKind Kind;
415 switch (TagSpec) {
416 default: assert(0 && "Unknown tag type!");
417 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
418 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
419 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
420 }
421
422 // There is no such thing as an unnamed class template.
423 if (!Name) {
424 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregorc5d6fa72009-03-25 00:13:59 +0000425 return true;
Douglas Gregord406b032009-02-06 22:42:48 +0000426 }
427
428 // Find any previous declaration with this name.
429 LookupResult Previous = LookupParsedName(S, &SS, Name, LookupOrdinaryName,
430 true);
431 assert(!Previous.isAmbiguous() && "Ambiguity in class template redecl?");
432 NamedDecl *PrevDecl = 0;
433 if (Previous.begin() != Previous.end())
434 PrevDecl = *Previous.begin();
435
436 DeclContext *SemanticContext = CurContext;
437 if (SS.isNotEmpty() && !SS.isInvalid()) {
Douglas Gregor734b4ba2009-03-19 00:18:19 +0000438 SemanticContext = computeDeclContext(SS);
Douglas Gregord406b032009-02-06 22:42:48 +0000439
440 // FIXME: need to match up several levels of template parameter
441 // lists here.
442 }
443
444 // FIXME: member templates!
445 TemplateParameterList *TemplateParams
446 = static_cast<TemplateParameterList *>(*TemplateParameterLists.release());
447
448 // If there is a previous declaration with the same name, check
449 // whether this is a valid redeclaration.
450 ClassTemplateDecl *PrevClassTemplate
451 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
452 if (PrevClassTemplate) {
453 // Ensure that the template parameter lists are compatible.
454 if (!TemplateParameterListsAreEqual(TemplateParams,
455 PrevClassTemplate->getTemplateParameters(),
456 /*Complain=*/true))
Douglas Gregorc5d6fa72009-03-25 00:13:59 +0000457 return true;
Douglas Gregord406b032009-02-06 22:42:48 +0000458
459 // C++ [temp.class]p4:
460 // In a redeclaration, partial specialization, explicit
461 // specialization or explicit instantiation of a class template,
462 // the class-key shall agree in kind with the original class
463 // template declaration (7.1.5.3).
464 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
465 if (PrevRecordDecl->getTagKind() != Kind) {
466 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
467 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregorc5d6fa72009-03-25 00:13:59 +0000468 return true;
Douglas Gregord406b032009-02-06 22:42:48 +0000469 }
470
471
472 // Check for redefinition of this class template.
473 if (TK == TK_Definition) {
474 if (TagDecl *Def = PrevRecordDecl->getDefinition(Context)) {
475 Diag(NameLoc, diag::err_redefinition) << Name;
476 Diag(Def->getLocation(), diag::note_previous_definition);
477 // FIXME: Would it make sense to try to "forget" the previous
478 // definition, as part of error recovery?
Douglas Gregorc5d6fa72009-03-25 00:13:59 +0000479 return true;
Douglas Gregord406b032009-02-06 22:42:48 +0000480 }
481 }
482 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
483 // Maybe we will complain about the shadowed template parameter.
484 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
485 // Just pretend that we didn't see the previous declaration.
486 PrevDecl = 0;
487 } else if (PrevDecl) {
488 // C++ [temp]p5:
489 // A class template shall not have the same name as any other
490 // template, class, function, object, enumeration, enumerator,
491 // namespace, or type in the same scope (3.3), except as specified
492 // in (14.5.4).
493 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
494 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregorc5d6fa72009-03-25 00:13:59 +0000495 return true;
Douglas Gregord406b032009-02-06 22:42:48 +0000496 }
497
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000498 // Check the template parameter list of this declaration, possibly
499 // merging in the template parameter list from the previous class
500 // template declaration.
501 if (CheckTemplateParameterList(TemplateParams,
502 PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0))
503 Invalid = true;
504
Douglas Gregord406b032009-02-06 22:42:48 +0000505 // If we had a scope specifier, we better have a previous template
506 // declaration!
507
Douglas Gregor55216ac2009-03-26 00:10:35 +0000508 CXXRecordDecl *NewClass =
Douglas Gregord406b032009-02-06 22:42:48 +0000509 CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name,
510 PrevClassTemplate?
511 PrevClassTemplate->getTemplatedDecl() : 0);
512
513 ClassTemplateDecl *NewTemplate
514 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
515 DeclarationName(Name), TemplateParams,
Douglas Gregor47bde7c2009-03-19 17:26:29 +0000516 NewClass, PrevClassTemplate);
Douglas Gregor55216ac2009-03-26 00:10:35 +0000517 NewClass->setDescribedClassTemplate(NewTemplate);
518
Anders Carlsson4ca43492009-03-26 01:24:28 +0000519 // Set the access specifier.
520 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
521
Douglas Gregord406b032009-02-06 22:42:48 +0000522 // Set the lexical context of these templates
523 NewClass->setLexicalDeclContext(CurContext);
524 NewTemplate->setLexicalDeclContext(CurContext);
525
526 if (TK == TK_Definition)
527 NewClass->startDefinition();
528
529 if (Attr)
530 ProcessDeclAttributeList(NewClass, Attr);
531
532 PushOnScopeChains(NewTemplate, S);
533
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000534 if (Invalid) {
535 NewTemplate->setInvalidDecl();
536 NewClass->setInvalidDecl();
537 }
Chris Lattner5261d0c2009-03-28 19:18:32 +0000538 return DeclPtrTy::make(NewTemplate);
Douglas Gregord406b032009-02-06 22:42:48 +0000539}
540
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000541/// \brief Checks the validity of a template parameter list, possibly
542/// considering the template parameter list from a previous
543/// declaration.
544///
545/// If an "old" template parameter list is provided, it must be
546/// equivalent (per TemplateParameterListsAreEqual) to the "new"
547/// template parameter list.
548///
549/// \param NewParams Template parameter list for a new template
550/// declaration. This template parameter list will be updated with any
551/// default arguments that are carried through from the previous
552/// template parameter list.
553///
554/// \param OldParams If provided, template parameter list from a
555/// previous declaration of the same template. Default template
556/// arguments will be merged from the old template parameter list to
557/// the new template parameter list.
558///
559/// \returns true if an error occurred, false otherwise.
560bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
561 TemplateParameterList *OldParams) {
562 bool Invalid = false;
563
564 // C++ [temp.param]p10:
565 // The set of default template-arguments available for use with a
566 // template declaration or definition is obtained by merging the
567 // default arguments from the definition (if in scope) and all
568 // declarations in scope in the same way default function
569 // arguments are (8.3.6).
570 bool SawDefaultArgument = false;
571 SourceLocation PreviousDefaultArgLoc;
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000572
Mike Stumpe0b7e032009-02-11 23:03:27 +0000573 // Dummy initialization to avoid warnings.
Douglas Gregorc5363f42009-02-11 20:46:19 +0000574 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000575 if (OldParams)
576 OldParam = OldParams->begin();
577
578 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
579 NewParamEnd = NewParams->end();
580 NewParam != NewParamEnd; ++NewParam) {
581 // Variables used to diagnose redundant default arguments
582 bool RedundantDefaultArg = false;
583 SourceLocation OldDefaultLoc;
584 SourceLocation NewDefaultLoc;
585
586 // Variables used to diagnose missing default arguments
587 bool MissingDefaultArg = false;
588
589 // Merge default arguments for template type parameters.
590 if (TemplateTypeParmDecl *NewTypeParm
591 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
592 TemplateTypeParmDecl *OldTypeParm
593 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
594
595 if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
596 NewTypeParm->hasDefaultArgument()) {
597 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
598 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
599 SawDefaultArgument = true;
600 RedundantDefaultArg = true;
601 PreviousDefaultArgLoc = NewDefaultLoc;
602 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
603 // Merge the default argument from the old declaration to the
604 // new declaration.
605 SawDefaultArgument = true;
606 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgument(),
607 OldTypeParm->getDefaultArgumentLoc(),
608 true);
609 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
610 } else if (NewTypeParm->hasDefaultArgument()) {
611 SawDefaultArgument = true;
612 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
613 } else if (SawDefaultArgument)
614 MissingDefaultArg = true;
615 }
616 // Merge default arguments for non-type template parameters
617 else if (NonTypeTemplateParmDecl *NewNonTypeParm
618 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
619 NonTypeTemplateParmDecl *OldNonTypeParm
620 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
621 if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
622 NewNonTypeParm->hasDefaultArgument()) {
623 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
624 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
625 SawDefaultArgument = true;
626 RedundantDefaultArg = true;
627 PreviousDefaultArgLoc = NewDefaultLoc;
628 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
629 // Merge the default argument from the old declaration to the
630 // new declaration.
631 SawDefaultArgument = true;
632 // FIXME: We need to create a new kind of "default argument"
633 // expression that points to a previous template template
634 // parameter.
635 NewNonTypeParm->setDefaultArgument(
636 OldNonTypeParm->getDefaultArgument());
637 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
638 } else if (NewNonTypeParm->hasDefaultArgument()) {
639 SawDefaultArgument = true;
640 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
641 } else if (SawDefaultArgument)
642 MissingDefaultArg = true;
643 }
644 // Merge default arguments for template template parameters
645 else {
646 TemplateTemplateParmDecl *NewTemplateParm
647 = cast<TemplateTemplateParmDecl>(*NewParam);
648 TemplateTemplateParmDecl *OldTemplateParm
649 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
650 if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
651 NewTemplateParm->hasDefaultArgument()) {
652 OldDefaultLoc = OldTemplateParm->getDefaultArgumentLoc();
653 NewDefaultLoc = NewTemplateParm->getDefaultArgumentLoc();
654 SawDefaultArgument = true;
655 RedundantDefaultArg = true;
656 PreviousDefaultArgLoc = NewDefaultLoc;
657 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
658 // Merge the default argument from the old declaration to the
659 // new declaration.
660 SawDefaultArgument = true;
661 // FIXME: We need to create a new kind of "default argument"
662 // expression that points to a previous template template
663 // parameter.
664 NewTemplateParm->setDefaultArgument(
665 OldTemplateParm->getDefaultArgument());
666 PreviousDefaultArgLoc = OldTemplateParm->getDefaultArgumentLoc();
667 } else if (NewTemplateParm->hasDefaultArgument()) {
668 SawDefaultArgument = true;
669 PreviousDefaultArgLoc = NewTemplateParm->getDefaultArgumentLoc();
670 } else if (SawDefaultArgument)
671 MissingDefaultArg = true;
672 }
673
674 if (RedundantDefaultArg) {
675 // C++ [temp.param]p12:
676 // A template-parameter shall not be given default arguments
677 // by two different declarations in the same scope.
678 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
679 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
680 Invalid = true;
681 } else if (MissingDefaultArg) {
682 // C++ [temp.param]p11:
683 // If a template-parameter has a default template-argument,
684 // all subsequent template-parameters shall have a default
685 // template-argument supplied.
686 Diag((*NewParam)->getLocation(),
687 diag::err_template_param_default_arg_missing);
688 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
689 Invalid = true;
690 }
691
692 // If we have an old template parameter list that we're merging
693 // in, move on to the next parameter.
694 if (OldParams)
695 ++OldParam;
696 }
697
698 return Invalid;
699}
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000700
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000701/// \brief Translates template arguments as provided by the parser
702/// into template arguments used by semantic analysis.
703static void
704translateTemplateArguments(ASTTemplateArgsPtr &TemplateArgsIn,
705 SourceLocation *TemplateArgLocs,
706 llvm::SmallVector<TemplateArgument, 16> &TemplateArgs) {
707 TemplateArgs.reserve(TemplateArgsIn.size());
708
709 void **Args = TemplateArgsIn.getArgs();
710 bool *ArgIsType = TemplateArgsIn.getArgIsType();
711 for (unsigned Arg = 0, Last = TemplateArgsIn.size(); Arg != Last; ++Arg) {
712 TemplateArgs.push_back(
713 ArgIsType[Arg]? TemplateArgument(TemplateArgLocs[Arg],
714 QualType::getFromOpaquePtr(Args[Arg]))
715 : TemplateArgument(reinterpret_cast<Expr *>(Args[Arg])));
716 }
717}
718
Douglas Gregordd13e842009-03-30 22:58:21 +0000719QualType Sema::CheckTemplateIdType(TemplateName Name,
720 SourceLocation TemplateLoc,
721 SourceLocation LAngleLoc,
722 const TemplateArgument *TemplateArgs,
723 unsigned NumTemplateArgs,
724 SourceLocation RAngleLoc) {
725 TemplateDecl *Template = Name.getAsTemplateDecl();
726 assert(Template && "Cannot handle dependent template-names yet");
727
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000728 // Check that the template argument list is well-formed for this
729 // template.
730 llvm::SmallVector<TemplateArgument, 16> ConvertedTemplateArgs;
Douglas Gregordd13e842009-03-30 22:58:21 +0000731 if (CheckTemplateArgumentList(Template, TemplateLoc, LAngleLoc,
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000732 TemplateArgs, NumTemplateArgs, RAngleLoc,
733 ConvertedTemplateArgs))
734 return QualType();
735
736 assert((ConvertedTemplateArgs.size() ==
Douglas Gregordd13e842009-03-30 22:58:21 +0000737 Template->getTemplateParameters()->size()) &&
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000738 "Converted template argument list is too short!");
739
740 QualType CanonType;
741
Douglas Gregordd13e842009-03-30 22:58:21 +0000742 if (TemplateSpecializationType::anyDependentTemplateArguments(
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000743 TemplateArgs,
744 NumTemplateArgs)) {
745 // This class template specialization is a dependent
746 // type. Therefore, its canonical type is another class template
747 // specialization type that contains all of the converted
748 // arguments in canonical form. This ensures that, e.g., A<T> and
749 // A<T, T> have identical types when A is declared as:
750 //
751 // template<typename T, typename U = T> struct A;
752
Douglas Gregordd13e842009-03-30 22:58:21 +0000753 CanonType = Context.getTemplateSpecializationType(Name,
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000754 &ConvertedTemplateArgs[0],
755 ConvertedTemplateArgs.size());
Douglas Gregordd13e842009-03-30 22:58:21 +0000756 } else if (ClassTemplateDecl *ClassTemplate
757 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000758 // Find the class template specialization declaration that
759 // corresponds to these arguments.
760 llvm::FoldingSetNodeID ID;
761 ClassTemplateSpecializationDecl::Profile(ID, &ConvertedTemplateArgs[0],
762 ConvertedTemplateArgs.size());
763 void *InsertPos = 0;
764 ClassTemplateSpecializationDecl *Decl
765 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
766 if (!Decl) {
767 // This is the first time we have referenced this class template
768 // specialization. Create the canonical declaration and add it to
769 // the set of specializations.
770 Decl = ClassTemplateSpecializationDecl::Create(Context,
771 ClassTemplate->getDeclContext(),
772 TemplateLoc,
773 ClassTemplate,
774 &ConvertedTemplateArgs[0],
775 ConvertedTemplateArgs.size(),
776 0);
777 ClassTemplate->getSpecializations().InsertNode(Decl, InsertPos);
778 Decl->setLexicalDeclContext(CurContext);
779 }
780
781 CanonType = Context.getTypeDeclType(Decl);
782 }
783
784 // Build the fully-sugared type for this class template
785 // specialization, which refers back to the class template
786 // specialization we created or found.
Douglas Gregordd13e842009-03-30 22:58:21 +0000787 return Context.getTemplateSpecializationType(Name, TemplateArgs,
788 NumTemplateArgs, CanonType);
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000789}
790
Douglas Gregora08b6c72009-02-17 23:15:12 +0000791Action::TypeResult
Douglas Gregordd13e842009-03-30 22:58:21 +0000792Sema::ActOnTemplateIdType(TemplateTy TemplateD, SourceLocation TemplateLoc,
793 SourceLocation LAngleLoc,
794 ASTTemplateArgsPtr TemplateArgsIn,
795 SourceLocation *TemplateArgLocs,
796 SourceLocation RAngleLoc) {
797 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Douglas Gregor8e458f42009-02-09 18:46:07 +0000798
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000799 // Translate the parser's template argument list in our AST format.
800 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
801 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000802
Douglas Gregordd13e842009-03-30 22:58:21 +0000803 QualType Result = CheckTemplateIdType(Template, TemplateLoc, LAngleLoc,
804 &TemplateArgs[0], TemplateArgs.size(),
805 RAngleLoc);
Douglas Gregor8c795a12009-03-19 00:39:20 +0000806
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000807 TemplateArgsIn.release();
Douglas Gregor6f37b582009-02-09 19:34:22 +0000808 return Result.getAsOpaquePtr();
Douglas Gregor8e458f42009-02-09 18:46:07 +0000809}
810
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000811/// \brief Check that the given template argument list is well-formed
812/// for specializing the given template.
813bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
814 SourceLocation TemplateLoc,
815 SourceLocation LAngleLoc,
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000816 const TemplateArgument *TemplateArgs,
817 unsigned NumTemplateArgs,
Douglas Gregorad964b32009-02-17 01:05:43 +0000818 SourceLocation RAngleLoc,
819 llvm::SmallVectorImpl<TemplateArgument> &Converted) {
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000820 TemplateParameterList *Params = Template->getTemplateParameters();
821 unsigned NumParams = Params->size();
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000822 unsigned NumArgs = NumTemplateArgs;
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000823 bool Invalid = false;
824
825 if (NumArgs > NumParams ||
Douglas Gregorc347d8e2009-02-11 18:16:40 +0000826 NumArgs < Params->getMinRequiredArguments()) {
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000827 // FIXME: point at either the first arg beyond what we can handle,
828 // or the '>', depending on whether we have too many or too few
829 // arguments.
830 SourceRange Range;
831 if (NumArgs > NumParams)
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000832 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000833 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
834 << (NumArgs > NumParams)
835 << (isa<ClassTemplateDecl>(Template)? 0 :
836 isa<FunctionTemplateDecl>(Template)? 1 :
837 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
838 << Template << Range;
Douglas Gregorc347d8e2009-02-11 18:16:40 +0000839 Diag(Template->getLocation(), diag::note_template_decl_here)
840 << Params->getSourceRange();
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000841 Invalid = true;
842 }
843
844 // C++ [temp.arg]p1:
845 // [...] The type and form of each template-argument specified in
846 // a template-id shall match the type and form specified for the
847 // corresponding parameter declared by the template in its
848 // template-parameter-list.
849 unsigned ArgIdx = 0;
850 for (TemplateParameterList::iterator Param = Params->begin(),
851 ParamEnd = Params->end();
852 Param != ParamEnd; ++Param, ++ArgIdx) {
853 // Decode the template argument
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000854 TemplateArgument Arg;
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000855 if (ArgIdx >= NumArgs) {
Douglas Gregorad964b32009-02-17 01:05:43 +0000856 // Retrieve the default template argument from the template
857 // parameter.
858 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
859 if (!TTP->hasDefaultArgument())
860 break;
861
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000862 QualType ArgType = TTP->getDefaultArgument();
Douglas Gregor74296542009-02-27 19:31:52 +0000863
864 // If the argument type is dependent, instantiate it now based
865 // on the previously-computed template arguments.
Douglas Gregor56d25a72009-03-10 20:44:00 +0000866 if (ArgType->isDependentType()) {
867 InstantiatingTemplate Inst(*this, TemplateLoc,
868 Template, &Converted[0],
869 Converted.size(),
870 SourceRange(TemplateLoc, RAngleLoc));
Douglas Gregor74296542009-02-27 19:31:52 +0000871 ArgType = InstantiateType(ArgType, &Converted[0], Converted.size(),
872 TTP->getDefaultArgumentLoc(),
873 TTP->getDeclName());
Douglas Gregor56d25a72009-03-10 20:44:00 +0000874 }
Douglas Gregor74296542009-02-27 19:31:52 +0000875
876 if (ArgType.isNull())
Douglas Gregorf57dcd02009-02-28 00:25:32 +0000877 return true;
Douglas Gregor74296542009-02-27 19:31:52 +0000878
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000879 Arg = TemplateArgument(TTP->getLocation(), ArgType);
Douglas Gregorad964b32009-02-17 01:05:43 +0000880 } else if (NonTypeTemplateParmDecl *NTTP
881 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
882 if (!NTTP->hasDefaultArgument())
883 break;
884
Douglas Gregored3a3982009-03-03 04:44:36 +0000885 // FIXME: Instantiate default argument
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000886 Arg = TemplateArgument(NTTP->getDefaultArgument());
Douglas Gregorad964b32009-02-17 01:05:43 +0000887 } else {
888 TemplateTemplateParmDecl *TempParm
889 = cast<TemplateTemplateParmDecl>(*Param);
890
891 if (!TempParm->hasDefaultArgument())
892 break;
893
Douglas Gregored3a3982009-03-03 04:44:36 +0000894 // FIXME: Instantiate default argument
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000895 Arg = TemplateArgument(TempParm->getDefaultArgument());
Douglas Gregorad964b32009-02-17 01:05:43 +0000896 }
897 } else {
898 // Retrieve the template argument produced by the user.
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000899 Arg = TemplateArgs[ArgIdx];
Douglas Gregorad964b32009-02-17 01:05:43 +0000900 }
901
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000902
903 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
904 // Check template type parameters.
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000905 if (Arg.getKind() == TemplateArgument::Type) {
906 if (CheckTemplateArgument(TTP, Arg.getAsType(), Arg.getLocation()))
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000907 Invalid = true;
Douglas Gregorad964b32009-02-17 01:05:43 +0000908
909 // Add the converted template type argument.
910 Converted.push_back(
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000911 TemplateArgument(Arg.getLocation(),
912 Context.getCanonicalType(Arg.getAsType())));
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000913 continue;
914 }
915
916 // C++ [temp.arg.type]p1:
917 // A template-argument for a template-parameter which is a
918 // type shall be a type-id.
919
920 // We have a template type parameter but the template argument
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000921 // is not a type.
922 Diag(Arg.getLocation(), diag::err_template_arg_must_be_type);
Douglas Gregor341ac792009-02-10 00:53:15 +0000923 Diag((*Param)->getLocation(), diag::note_template_param_here);
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000924 Invalid = true;
925 } else if (NonTypeTemplateParmDecl *NTTP
926 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
927 // Check non-type template parameters.
Douglas Gregored3a3982009-03-03 04:44:36 +0000928
929 // Instantiate the type of the non-type template parameter with
930 // the template arguments we've seen thus far.
931 QualType NTTPType = NTTP->getType();
932 if (NTTPType->isDependentType()) {
933 // Instantiate the type of the non-type template parameter.
Douglas Gregor56d25a72009-03-10 20:44:00 +0000934 InstantiatingTemplate Inst(*this, TemplateLoc,
935 Template, &Converted[0],
936 Converted.size(),
937 SourceRange(TemplateLoc, RAngleLoc));
938
Douglas Gregored3a3982009-03-03 04:44:36 +0000939 NTTPType = InstantiateType(NTTPType,
940 &Converted[0], Converted.size(),
941 NTTP->getLocation(),
942 NTTP->getDeclName());
943 // If that worked, check the non-type template parameter type
944 // for validity.
945 if (!NTTPType.isNull())
946 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
947 NTTP->getLocation());
948
949 if (NTTPType.isNull()) {
950 Invalid = true;
951 break;
952 }
953 }
954
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000955 switch (Arg.getKind()) {
956 case TemplateArgument::Expression: {
957 Expr *E = Arg.getAsExpr();
958 if (CheckTemplateArgument(NTTP, NTTPType, E, &Converted))
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000959 Invalid = true;
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000960 break;
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000961 }
962
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000963 case TemplateArgument::Declaration:
964 case TemplateArgument::Integral:
965 // We've already checked this template argument, so just copy
966 // it to the list of converted arguments.
967 Converted.push_back(Arg);
968 break;
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000969
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000970 case TemplateArgument::Type:
971 // We have a non-type template parameter but the template
972 // argument is a type.
973
974 // C++ [temp.arg]p2:
975 // In a template-argument, an ambiguity between a type-id and
976 // an expression is resolved to a type-id, regardless of the
977 // form of the corresponding template-parameter.
978 //
979 // We warn specifically about this case, since it can be rather
980 // confusing for users.
981 if (Arg.getAsType()->isFunctionType())
982 Diag(Arg.getLocation(), diag::err_template_arg_nontype_ambig)
983 << Arg.getAsType();
984 else
985 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr);
986 Diag((*Param)->getLocation(), diag::note_template_param_here);
987 Invalid = true;
988 }
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000989 } else {
990 // Check template template parameters.
991 TemplateTemplateParmDecl *TempParm
992 = cast<TemplateTemplateParmDecl>(*Param);
993
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000994 switch (Arg.getKind()) {
995 case TemplateArgument::Expression: {
996 Expr *ArgExpr = Arg.getAsExpr();
997 if (ArgExpr && isa<DeclRefExpr>(ArgExpr) &&
998 isa<TemplateDecl>(cast<DeclRefExpr>(ArgExpr)->getDecl())) {
999 if (CheckTemplateArgument(TempParm, cast<DeclRefExpr>(ArgExpr)))
1000 Invalid = true;
1001
1002 // Add the converted template argument.
1003 // FIXME: Need the "canonical" template declaration!
1004 Converted.push_back(
1005 TemplateArgument(Arg.getLocation(),
1006 cast<DeclRefExpr>(ArgExpr)->getDecl()));
1007 continue;
1008 }
1009 }
1010 // fall through
1011
1012 case TemplateArgument::Type: {
1013 // We have a template template parameter but the template
1014 // argument does not refer to a template.
1015 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
1016 Invalid = true;
1017 break;
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001018 }
1019
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001020 case TemplateArgument::Declaration:
1021 // We've already checked this template argument, so just copy
1022 // it to the list of converted arguments.
1023 Converted.push_back(Arg);
1024 break;
1025
1026 case TemplateArgument::Integral:
1027 assert(false && "Integral argument with template template parameter");
1028 break;
1029 }
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001030 }
1031 }
1032
1033 return Invalid;
1034}
1035
1036/// \brief Check a template argument against its corresponding
1037/// template type parameter.
1038///
1039/// This routine implements the semantics of C++ [temp.arg.type]. It
1040/// returns true if an error occurred, and false otherwise.
1041bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
1042 QualType Arg, SourceLocation ArgLoc) {
1043 // C++ [temp.arg.type]p2:
1044 // A local type, a type with no linkage, an unnamed type or a type
1045 // compounded from any of these types shall not be used as a
1046 // template-argument for a template type-parameter.
1047 //
1048 // FIXME: Perform the recursive and no-linkage type checks.
1049 const TagType *Tag = 0;
1050 if (const EnumType *EnumT = Arg->getAsEnumType())
1051 Tag = EnumT;
1052 else if (const RecordType *RecordT = Arg->getAsRecordType())
1053 Tag = RecordT;
1054 if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod())
1055 return Diag(ArgLoc, diag::err_template_arg_local_type)
1056 << QualType(Tag, 0);
Douglas Gregor04385782009-03-10 18:33:27 +00001057 else if (Tag && !Tag->getDecl()->getDeclName() &&
1058 !Tag->getDecl()->getTypedefForAnonDecl()) {
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001059 Diag(ArgLoc, diag::err_template_arg_unnamed_type);
1060 Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here);
1061 return true;
1062 }
1063
1064 return false;
1065}
1066
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001067/// \brief Checks whether the given template argument is the address
1068/// of an object or function according to C++ [temp.arg.nontype]p1.
Douglas Gregorad964b32009-02-17 01:05:43 +00001069bool Sema::CheckTemplateArgumentAddressOfObjectOrFunction(Expr *Arg,
1070 NamedDecl *&Entity) {
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001071 bool Invalid = false;
1072
1073 // See through any implicit casts we added to fix the type.
1074 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
1075 Arg = Cast->getSubExpr();
1076
1077 // C++ [temp.arg.nontype]p1:
1078 //
1079 // A template-argument for a non-type, non-template
1080 // template-parameter shall be one of: [...]
1081 //
1082 // -- the address of an object or function with external
1083 // linkage, including function templates and function
1084 // template-ids but excluding non-static class members,
1085 // expressed as & id-expression where the & is optional if
1086 // the name refers to a function or array, or if the
1087 // corresponding template-parameter is a reference; or
1088 DeclRefExpr *DRE = 0;
1089
1090 // Ignore (and complain about) any excess parentheses.
1091 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
1092 if (!Invalid) {
1093 Diag(Arg->getSourceRange().getBegin(),
1094 diag::err_template_arg_extra_parens)
1095 << Arg->getSourceRange();
1096 Invalid = true;
1097 }
1098
1099 Arg = Parens->getSubExpr();
1100 }
1101
1102 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
1103 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
1104 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
1105 } else
1106 DRE = dyn_cast<DeclRefExpr>(Arg);
1107
1108 if (!DRE || !isa<ValueDecl>(DRE->getDecl()))
1109 return Diag(Arg->getSourceRange().getBegin(),
1110 diag::err_template_arg_not_object_or_func_form)
1111 << Arg->getSourceRange();
1112
1113 // Cannot refer to non-static data members
1114 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl()))
1115 return Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
1116 << Field << Arg->getSourceRange();
1117
1118 // Cannot refer to non-static member functions
1119 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
1120 if (!Method->isStatic())
1121 return Diag(Arg->getSourceRange().getBegin(),
1122 diag::err_template_arg_method)
1123 << Method << Arg->getSourceRange();
1124
1125 // Functions must have external linkage.
1126 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
1127 if (Func->getStorageClass() == FunctionDecl::Static) {
1128 Diag(Arg->getSourceRange().getBegin(),
1129 diag::err_template_arg_function_not_extern)
1130 << Func << Arg->getSourceRange();
1131 Diag(Func->getLocation(), diag::note_template_arg_internal_object)
1132 << true;
1133 return true;
1134 }
1135
1136 // Okay: we've named a function with external linkage.
Douglas Gregorad964b32009-02-17 01:05:43 +00001137 Entity = Func;
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001138 return Invalid;
1139 }
1140
1141 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
1142 if (!Var->hasGlobalStorage()) {
1143 Diag(Arg->getSourceRange().getBegin(),
1144 diag::err_template_arg_object_not_extern)
1145 << Var << Arg->getSourceRange();
1146 Diag(Var->getLocation(), diag::note_template_arg_internal_object)
1147 << true;
1148 return true;
1149 }
1150
1151 // Okay: we've named an object with external linkage
Douglas Gregorad964b32009-02-17 01:05:43 +00001152 Entity = Var;
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001153 return Invalid;
1154 }
1155
1156 // We found something else, but we don't know specifically what it is.
1157 Diag(Arg->getSourceRange().getBegin(),
1158 diag::err_template_arg_not_object_or_func)
1159 << Arg->getSourceRange();
1160 Diag(DRE->getDecl()->getLocation(),
1161 diag::note_template_arg_refers_here);
1162 return true;
1163}
1164
1165/// \brief Checks whether the given template argument is a pointer to
1166/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregorad964b32009-02-17 01:05:43 +00001167bool
1168Sema::CheckTemplateArgumentPointerToMember(Expr *Arg, NamedDecl *&Member) {
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001169 bool Invalid = false;
1170
1171 // See through any implicit casts we added to fix the type.
1172 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
1173 Arg = Cast->getSubExpr();
1174
1175 // C++ [temp.arg.nontype]p1:
1176 //
1177 // A template-argument for a non-type, non-template
1178 // template-parameter shall be one of: [...]
1179 //
1180 // -- a pointer to member expressed as described in 5.3.1.
1181 QualifiedDeclRefExpr *DRE = 0;
1182
1183 // Ignore (and complain about) any excess parentheses.
1184 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
1185 if (!Invalid) {
1186 Diag(Arg->getSourceRange().getBegin(),
1187 diag::err_template_arg_extra_parens)
1188 << Arg->getSourceRange();
1189 Invalid = true;
1190 }
1191
1192 Arg = Parens->getSubExpr();
1193 }
1194
1195 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg))
1196 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
1197 DRE = dyn_cast<QualifiedDeclRefExpr>(UnOp->getSubExpr());
1198
1199 if (!DRE)
1200 return Diag(Arg->getSourceRange().getBegin(),
1201 diag::err_template_arg_not_pointer_to_member_form)
1202 << Arg->getSourceRange();
1203
1204 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
1205 assert((isa<FieldDecl>(DRE->getDecl()) ||
1206 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
1207 "Only non-static member pointers can make it here");
1208
1209 // Okay: this is the address of a non-static member, and therefore
1210 // a member pointer constant.
Douglas Gregorad964b32009-02-17 01:05:43 +00001211 Member = DRE->getDecl();
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001212 return Invalid;
1213 }
1214
1215 // We found something else, but we don't know specifically what it is.
1216 Diag(Arg->getSourceRange().getBegin(),
1217 diag::err_template_arg_not_pointer_to_member_form)
1218 << Arg->getSourceRange();
1219 Diag(DRE->getDecl()->getLocation(),
1220 diag::note_template_arg_refers_here);
1221 return true;
1222}
1223
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001224/// \brief Check a template argument against its corresponding
1225/// non-type template parameter.
1226///
Douglas Gregored3a3982009-03-03 04:44:36 +00001227/// This routine implements the semantics of C++ [temp.arg.nontype].
1228/// It returns true if an error occurred, and false otherwise. \p
1229/// InstantiatedParamType is the type of the non-type template
1230/// parameter after it has been instantiated.
Douglas Gregorad964b32009-02-17 01:05:43 +00001231///
1232/// If Converted is non-NULL and no errors occur, the value
1233/// of this argument will be added to the end of the Converted vector.
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001234bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Douglas Gregored3a3982009-03-03 04:44:36 +00001235 QualType InstantiatedParamType, Expr *&Arg,
Douglas Gregorad964b32009-02-17 01:05:43 +00001236 llvm::SmallVectorImpl<TemplateArgument> *Converted) {
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001237 SourceLocation StartLoc = Arg->getSourceRange().getBegin();
1238
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001239 // If either the parameter has a dependent type or the argument is
1240 // type-dependent, there's nothing we can check now.
Douglas Gregorad964b32009-02-17 01:05:43 +00001241 // FIXME: Add template argument to Converted!
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001242 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
1243 // FIXME: Produce a cloned, canonical expression?
1244 Converted->push_back(TemplateArgument(Arg));
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001245 return false;
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001246 }
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001247
1248 // C++ [temp.arg.nontype]p5:
1249 // The following conversions are performed on each expression used
1250 // as a non-type template-argument. If a non-type
1251 // template-argument cannot be converted to the type of the
1252 // corresponding template-parameter then the program is
1253 // ill-formed.
1254 //
1255 // -- for a non-type template-parameter of integral or
1256 // enumeration type, integral promotions (4.5) and integral
1257 // conversions (4.7) are applied.
Douglas Gregored3a3982009-03-03 04:44:36 +00001258 QualType ParamType = InstantiatedParamType;
Douglas Gregor2eedd992009-02-11 00:19:33 +00001259 QualType ArgType = Arg->getType();
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001260 if (ParamType->isIntegralType() || ParamType->isEnumeralType()) {
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001261 // C++ [temp.arg.nontype]p1:
1262 // A template-argument for a non-type, non-template
1263 // template-parameter shall be one of:
1264 //
1265 // -- an integral constant-expression of integral or enumeration
1266 // type; or
1267 // -- the name of a non-type template-parameter; or
1268 SourceLocation NonConstantLoc;
Douglas Gregorad964b32009-02-17 01:05:43 +00001269 llvm::APSInt Value;
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001270 if (!ArgType->isIntegralType() && !ArgType->isEnumeralType()) {
1271 Diag(Arg->getSourceRange().getBegin(),
1272 diag::err_template_arg_not_integral_or_enumeral)
1273 << ArgType << Arg->getSourceRange();
1274 Diag(Param->getLocation(), diag::note_template_param_here);
1275 return true;
1276 } else if (!Arg->isValueDependent() &&
Douglas Gregorad964b32009-02-17 01:05:43 +00001277 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001278 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
1279 << ArgType << Arg->getSourceRange();
1280 return true;
1281 }
1282
1283 // FIXME: We need some way to more easily get the unqualified form
1284 // of the types without going all the way to the
1285 // canonical type.
1286 if (Context.getCanonicalType(ParamType).getCVRQualifiers())
1287 ParamType = Context.getCanonicalType(ParamType).getUnqualifiedType();
1288 if (Context.getCanonicalType(ArgType).getCVRQualifiers())
1289 ArgType = Context.getCanonicalType(ArgType).getUnqualifiedType();
1290
1291 // Try to convert the argument to the parameter's type.
1292 if (ParamType == ArgType) {
1293 // Okay: no conversion necessary
1294 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
1295 !ParamType->isEnumeralType()) {
1296 // This is an integral promotion or conversion.
1297 ImpCastExprToType(Arg, ParamType);
1298 } else {
1299 // We can't perform this conversion.
1300 Diag(Arg->getSourceRange().getBegin(),
1301 diag::err_template_arg_not_convertible)
Douglas Gregored3a3982009-03-03 04:44:36 +00001302 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001303 Diag(Param->getLocation(), diag::note_template_param_here);
1304 return true;
1305 }
1306
Douglas Gregorafc86942009-03-14 00:20:21 +00001307 QualType IntegerType = Context.getCanonicalType(ParamType);
1308 if (const EnumType *Enum = IntegerType->getAsEnumType())
1309 IntegerType = Enum->getDecl()->getIntegerType();
1310
1311 if (!Arg->isValueDependent()) {
1312 // Check that an unsigned parameter does not receive a negative
1313 // value.
1314 if (IntegerType->isUnsignedIntegerType()
1315 && (Value.isSigned() && Value.isNegative())) {
1316 Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_negative)
1317 << Value.toString(10) << Param->getType()
1318 << Arg->getSourceRange();
1319 Diag(Param->getLocation(), diag::note_template_param_here);
1320 return true;
1321 }
1322
1323 // Check that we don't overflow the template parameter type.
1324 unsigned AllowedBits = Context.getTypeSize(IntegerType);
1325 if (Value.getActiveBits() > AllowedBits) {
1326 Diag(Arg->getSourceRange().getBegin(),
1327 diag::err_template_arg_too_large)
1328 << Value.toString(10) << Param->getType()
1329 << Arg->getSourceRange();
1330 Diag(Param->getLocation(), diag::note_template_param_here);
1331 return true;
1332 }
1333
1334 if (Value.getBitWidth() != AllowedBits)
1335 Value.extOrTrunc(AllowedBits);
1336 Value.setIsSigned(IntegerType->isSignedIntegerType());
1337 }
Douglas Gregorad964b32009-02-17 01:05:43 +00001338
1339 if (Converted) {
1340 // Add the value of this argument to the list of converted
1341 // arguments. We use the bitwidth and signedness of the template
1342 // parameter.
Douglas Gregor396f1142009-03-13 21:01:28 +00001343 if (Arg->isValueDependent()) {
1344 // The argument is value-dependent. Create a new
1345 // TemplateArgument with the converted expression.
1346 Converted->push_back(TemplateArgument(Arg));
1347 return false;
1348 }
1349
Douglas Gregor544cda62009-03-14 00:03:48 +00001350 Converted->push_back(TemplateArgument(StartLoc, Value,
Douglas Gregor63f5d602009-03-12 22:20:26 +00001351 Context.getCanonicalType(IntegerType)));
Douglas Gregorad964b32009-02-17 01:05:43 +00001352 }
1353
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001354 return false;
1355 }
Douglas Gregor2eedd992009-02-11 00:19:33 +00001356
Douglas Gregor3f411962009-02-11 01:18:59 +00001357 // Handle pointer-to-function, reference-to-function, and
1358 // pointer-to-member-function all in (roughly) the same way.
1359 if (// -- For a non-type template-parameter of type pointer to
1360 // function, only the function-to-pointer conversion (4.3) is
1361 // applied. If the template-argument represents a set of
1362 // overloaded functions (or a pointer to such), the matching
1363 // function is selected from the set (13.4).
1364 (ParamType->isPointerType() &&
1365 ParamType->getAsPointerType()->getPointeeType()->isFunctionType()) ||
1366 // -- For a non-type template-parameter of type reference to
1367 // function, no conversions apply. If the template-argument
1368 // represents a set of overloaded functions, the matching
1369 // function is selected from the set (13.4).
1370 (ParamType->isReferenceType() &&
1371 ParamType->getAsReferenceType()->getPointeeType()->isFunctionType()) ||
1372 // -- For a non-type template-parameter of type pointer to
1373 // member function, no conversions apply. If the
1374 // template-argument represents a set of overloaded member
1375 // functions, the matching member function is selected from
1376 // the set (13.4).
1377 (ParamType->isMemberPointerType() &&
1378 ParamType->getAsMemberPointerType()->getPointeeType()
1379 ->isFunctionType())) {
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001380 if (Context.hasSameUnqualifiedType(ArgType,
1381 ParamType.getNonReferenceType())) {
Douglas Gregor2eedd992009-02-11 00:19:33 +00001382 // We don't have to do anything: the types already match.
Douglas Gregor3f411962009-02-11 01:18:59 +00001383 } else if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregor2eedd992009-02-11 00:19:33 +00001384 ArgType = Context.getPointerType(ArgType);
1385 ImpCastExprToType(Arg, ArgType);
1386 } else if (FunctionDecl *Fn
1387 = ResolveAddressOfOverloadedFunction(Arg, ParamType, true)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00001388 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
1389 return true;
1390
Douglas Gregor2eedd992009-02-11 00:19:33 +00001391 FixOverloadedFunctionReference(Arg, Fn);
1392 ArgType = Arg->getType();
Douglas Gregor3f411962009-02-11 01:18:59 +00001393 if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregor2eedd992009-02-11 00:19:33 +00001394 ArgType = Context.getPointerType(Arg->getType());
1395 ImpCastExprToType(Arg, ArgType);
1396 }
1397 }
1398
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001399 if (!Context.hasSameUnqualifiedType(ArgType,
1400 ParamType.getNonReferenceType())) {
Douglas Gregor2eedd992009-02-11 00:19:33 +00001401 // We can't perform this conversion.
1402 Diag(Arg->getSourceRange().getBegin(),
1403 diag::err_template_arg_not_convertible)
Douglas Gregored3a3982009-03-03 04:44:36 +00001404 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor2eedd992009-02-11 00:19:33 +00001405 Diag(Param->getLocation(), diag::note_template_param_here);
1406 return true;
1407 }
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001408
Douglas Gregorad964b32009-02-17 01:05:43 +00001409 if (ParamType->isMemberPointerType()) {
1410 NamedDecl *Member = 0;
1411 if (CheckTemplateArgumentPointerToMember(Arg, Member))
1412 return true;
1413
1414 if (Converted)
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001415 Converted->push_back(TemplateArgument(StartLoc, Member));
Douglas Gregorad964b32009-02-17 01:05:43 +00001416
1417 return false;
1418 }
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001419
Douglas Gregorad964b32009-02-17 01:05:43 +00001420 NamedDecl *Entity = 0;
1421 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1422 return true;
1423
1424 if (Converted)
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001425 Converted->push_back(TemplateArgument(StartLoc, Entity));
Douglas Gregorad964b32009-02-17 01:05:43 +00001426 return false;
Douglas Gregor2eedd992009-02-11 00:19:33 +00001427 }
1428
Chris Lattner320dff22009-02-20 21:37:53 +00001429 if (ParamType->isPointerType()) {
Douglas Gregor3f411962009-02-11 01:18:59 +00001430 // -- for a non-type template-parameter of type pointer to
1431 // object, qualification conversions (4.4) and the
1432 // array-to-pointer conversion (4.2) are applied.
Douglas Gregor26ea1222009-03-24 20:32:41 +00001433 assert(ParamType->getAsPointerType()->getPointeeType()->isObjectType() &&
Douglas Gregor3f411962009-02-11 01:18:59 +00001434 "Only object pointers allowed here");
Douglas Gregord8c8c092009-02-11 00:44:29 +00001435
Douglas Gregor3f411962009-02-11 01:18:59 +00001436 if (ArgType->isArrayType()) {
1437 ArgType = Context.getArrayDecayedType(ArgType);
1438 ImpCastExprToType(Arg, ArgType);
Douglas Gregord8c8c092009-02-11 00:44:29 +00001439 }
Douglas Gregor3f411962009-02-11 01:18:59 +00001440
1441 if (IsQualificationConversion(ArgType, ParamType)) {
1442 ArgType = ParamType;
1443 ImpCastExprToType(Arg, ParamType);
1444 }
1445
Douglas Gregor0ea4e302009-02-11 18:22:40 +00001446 if (!Context.hasSameUnqualifiedType(ArgType, ParamType)) {
Douglas Gregor3f411962009-02-11 01:18:59 +00001447 // We can't perform this conversion.
1448 Diag(Arg->getSourceRange().getBegin(),
1449 diag::err_template_arg_not_convertible)
Douglas Gregored3a3982009-03-03 04:44:36 +00001450 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor3f411962009-02-11 01:18:59 +00001451 Diag(Param->getLocation(), diag::note_template_param_here);
1452 return true;
1453 }
1454
Douglas Gregorad964b32009-02-17 01:05:43 +00001455 NamedDecl *Entity = 0;
1456 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1457 return true;
1458
1459 if (Converted)
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001460 Converted->push_back(TemplateArgument(StartLoc, Entity));
Douglas Gregorad964b32009-02-17 01:05:43 +00001461
1462 return false;
Douglas Gregord8c8c092009-02-11 00:44:29 +00001463 }
Douglas Gregor3f411962009-02-11 01:18:59 +00001464
1465 if (const ReferenceType *ParamRefType = ParamType->getAsReferenceType()) {
1466 // -- For a non-type template-parameter of type reference to
1467 // object, no conversions apply. The type referred to by the
1468 // reference may be more cv-qualified than the (otherwise
1469 // identical) type of the template-argument. The
1470 // template-parameter is bound directly to the
1471 // template-argument, which must be an lvalue.
Douglas Gregor26ea1222009-03-24 20:32:41 +00001472 assert(ParamRefType->getPointeeType()->isObjectType() &&
Douglas Gregor3f411962009-02-11 01:18:59 +00001473 "Only object references allowed here");
Douglas Gregord8c8c092009-02-11 00:44:29 +00001474
Douglas Gregor0ea4e302009-02-11 18:22:40 +00001475 if (!Context.hasSameUnqualifiedType(ParamRefType->getPointeeType(), ArgType)) {
Douglas Gregor3f411962009-02-11 01:18:59 +00001476 Diag(Arg->getSourceRange().getBegin(),
1477 diag::err_template_arg_no_ref_bind)
Douglas Gregored3a3982009-03-03 04:44:36 +00001478 << InstantiatedParamType << Arg->getType()
Douglas Gregor3f411962009-02-11 01:18:59 +00001479 << Arg->getSourceRange();
1480 Diag(Param->getLocation(), diag::note_template_param_here);
1481 return true;
1482 }
1483
1484 unsigned ParamQuals
1485 = Context.getCanonicalType(ParamType).getCVRQualifiers();
1486 unsigned ArgQuals = Context.getCanonicalType(ArgType).getCVRQualifiers();
1487
1488 if ((ParamQuals | ArgQuals) != ParamQuals) {
1489 Diag(Arg->getSourceRange().getBegin(),
1490 diag::err_template_arg_ref_bind_ignores_quals)
Douglas Gregored3a3982009-03-03 04:44:36 +00001491 << InstantiatedParamType << Arg->getType()
Douglas Gregor3f411962009-02-11 01:18:59 +00001492 << Arg->getSourceRange();
1493 Diag(Param->getLocation(), diag::note_template_param_here);
1494 return true;
1495 }
1496
Douglas Gregorad964b32009-02-17 01:05:43 +00001497 NamedDecl *Entity = 0;
1498 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1499 return true;
1500
1501 if (Converted)
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001502 Converted->push_back(TemplateArgument(StartLoc, Entity));
Douglas Gregorad964b32009-02-17 01:05:43 +00001503
1504 return false;
Douglas Gregor3f411962009-02-11 01:18:59 +00001505 }
Douglas Gregor3628e1b2009-02-11 16:16:59 +00001506
1507 // -- For a non-type template-parameter of type pointer to data
1508 // member, qualification conversions (4.4) are applied.
1509 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
1510
Douglas Gregor0ea4e302009-02-11 18:22:40 +00001511 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
Douglas Gregor3628e1b2009-02-11 16:16:59 +00001512 // Types match exactly: nothing more to do here.
1513 } else if (IsQualificationConversion(ArgType, ParamType)) {
1514 ImpCastExprToType(Arg, ParamType);
1515 } else {
1516 // We can't perform this conversion.
1517 Diag(Arg->getSourceRange().getBegin(),
1518 diag::err_template_arg_not_convertible)
Douglas Gregored3a3982009-03-03 04:44:36 +00001519 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor3628e1b2009-02-11 16:16:59 +00001520 Diag(Param->getLocation(), diag::note_template_param_here);
1521 return true;
1522 }
1523
Douglas Gregorad964b32009-02-17 01:05:43 +00001524 NamedDecl *Member = 0;
1525 if (CheckTemplateArgumentPointerToMember(Arg, Member))
1526 return true;
1527
1528 if (Converted)
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001529 Converted->push_back(TemplateArgument(StartLoc, Member));
Douglas Gregorad964b32009-02-17 01:05:43 +00001530
1531 return false;
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001532}
1533
1534/// \brief Check a template argument against its corresponding
1535/// template template parameter.
1536///
1537/// This routine implements the semantics of C++ [temp.arg.template].
1538/// It returns true if an error occurred, and false otherwise.
1539bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
1540 DeclRefExpr *Arg) {
Douglas Gregore8e367f2009-02-10 00:24:35 +00001541 assert(isa<TemplateDecl>(Arg->getDecl()) && "Only template decls allowed");
1542 TemplateDecl *Template = cast<TemplateDecl>(Arg->getDecl());
1543
1544 // C++ [temp.arg.template]p1:
1545 // A template-argument for a template template-parameter shall be
1546 // the name of a class template, expressed as id-expression. Only
1547 // primary class templates are considered when matching the
1548 // template template argument with the corresponding parameter;
1549 // partial specializations are not considered even if their
1550 // parameter lists match that of the template template parameter.
1551 if (!isa<ClassTemplateDecl>(Template)) {
1552 assert(isa<FunctionTemplateDecl>(Template) &&
1553 "Only function templates are possible here");
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001554 Diag(Arg->getSourceRange().getBegin(),
1555 diag::note_template_arg_refers_here_func)
Douglas Gregore8e367f2009-02-10 00:24:35 +00001556 << Template;
1557 }
1558
1559 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
1560 Param->getTemplateParameters(),
1561 true, true,
1562 Arg->getSourceRange().getBegin());
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001563}
1564
Douglas Gregord406b032009-02-06 22:42:48 +00001565/// \brief Determine whether the given template parameter lists are
1566/// equivalent.
1567///
1568/// \param New The new template parameter list, typically written in the
1569/// source code as part of a new template declaration.
1570///
1571/// \param Old The old template parameter list, typically found via
1572/// name lookup of the template declared with this template parameter
1573/// list.
1574///
1575/// \param Complain If true, this routine will produce a diagnostic if
1576/// the template parameter lists are not equivalent.
1577///
Douglas Gregore8e367f2009-02-10 00:24:35 +00001578/// \param IsTemplateTemplateParm If true, this routine is being
1579/// called to compare the template parameter lists of a template
1580/// template parameter.
1581///
1582/// \param TemplateArgLoc If this source location is valid, then we
1583/// are actually checking the template parameter list of a template
1584/// argument (New) against the template parameter list of its
1585/// corresponding template template parameter (Old). We produce
1586/// slightly different diagnostics in this scenario.
1587///
Douglas Gregord406b032009-02-06 22:42:48 +00001588/// \returns True if the template parameter lists are equal, false
1589/// otherwise.
1590bool
1591Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
1592 TemplateParameterList *Old,
1593 bool Complain,
Douglas Gregore8e367f2009-02-10 00:24:35 +00001594 bool IsTemplateTemplateParm,
1595 SourceLocation TemplateArgLoc) {
Douglas Gregord406b032009-02-06 22:42:48 +00001596 if (Old->size() != New->size()) {
1597 if (Complain) {
Douglas Gregore8e367f2009-02-10 00:24:35 +00001598 unsigned NextDiag = diag::err_template_param_list_different_arity;
1599 if (TemplateArgLoc.isValid()) {
1600 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
1601 NextDiag = diag::note_template_param_list_different_arity;
1602 }
1603 Diag(New->getTemplateLoc(), NextDiag)
1604 << (New->size() > Old->size())
1605 << IsTemplateTemplateParm
1606 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
Douglas Gregord406b032009-02-06 22:42:48 +00001607 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
1608 << IsTemplateTemplateParm
1609 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
1610 }
1611
1612 return false;
1613 }
1614
1615 for (TemplateParameterList::iterator OldParm = Old->begin(),
1616 OldParmEnd = Old->end(), NewParm = New->begin();
1617 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
1618 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
Douglas Gregore8e367f2009-02-10 00:24:35 +00001619 unsigned NextDiag = diag::err_template_param_different_kind;
1620 if (TemplateArgLoc.isValid()) {
1621 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
1622 NextDiag = diag::note_template_param_different_kind;
1623 }
1624 Diag((*NewParm)->getLocation(), NextDiag)
Douglas Gregord406b032009-02-06 22:42:48 +00001625 << IsTemplateTemplateParm;
1626 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
1627 << IsTemplateTemplateParm;
1628 return false;
1629 }
1630
1631 if (isa<TemplateTypeParmDecl>(*OldParm)) {
1632 // Okay; all template type parameters are equivalent (since we
Douglas Gregore8e367f2009-02-10 00:24:35 +00001633 // know we're at the same index).
1634#if 0
1635 // FIXME: Enable this code in debug mode *after* we properly go
1636 // through and "instantiate" the template parameter lists of
1637 // template template parameters. It's only after this
1638 // instantiation that (1) any dependent types within the
1639 // template parameter list of the template template parameter
1640 // can be checked, and (2) the template type parameter depths
1641 // will match up.
Douglas Gregord406b032009-02-06 22:42:48 +00001642 QualType OldParmType
1643 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*OldParm));
1644 QualType NewParmType
1645 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*NewParm));
1646 assert(Context.getCanonicalType(OldParmType) ==
1647 Context.getCanonicalType(NewParmType) &&
1648 "type parameter mismatch?");
1649#endif
1650 } else if (NonTypeTemplateParmDecl *OldNTTP
1651 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
1652 // The types of non-type template parameters must agree.
1653 NonTypeTemplateParmDecl *NewNTTP
1654 = cast<NonTypeTemplateParmDecl>(*NewParm);
1655 if (Context.getCanonicalType(OldNTTP->getType()) !=
1656 Context.getCanonicalType(NewNTTP->getType())) {
1657 if (Complain) {
Douglas Gregore8e367f2009-02-10 00:24:35 +00001658 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
1659 if (TemplateArgLoc.isValid()) {
1660 Diag(TemplateArgLoc,
1661 diag::err_template_arg_template_params_mismatch);
1662 NextDiag = diag::note_template_nontype_parm_different_type;
1663 }
1664 Diag(NewNTTP->getLocation(), NextDiag)
Douglas Gregord406b032009-02-06 22:42:48 +00001665 << NewNTTP->getType()
1666 << IsTemplateTemplateParm;
1667 Diag(OldNTTP->getLocation(),
1668 diag::note_template_nontype_parm_prev_declaration)
1669 << OldNTTP->getType();
1670 }
1671 return false;
1672 }
1673 } else {
1674 // The template parameter lists of template template
1675 // parameters must agree.
1676 // FIXME: Could we perform a faster "type" comparison here?
1677 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
1678 "Only template template parameters handled here");
1679 TemplateTemplateParmDecl *OldTTP
1680 = cast<TemplateTemplateParmDecl>(*OldParm);
1681 TemplateTemplateParmDecl *NewTTP
1682 = cast<TemplateTemplateParmDecl>(*NewParm);
1683 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
1684 OldTTP->getTemplateParameters(),
1685 Complain,
Douglas Gregore8e367f2009-02-10 00:24:35 +00001686 /*IsTemplateTemplateParm=*/true,
1687 TemplateArgLoc))
Douglas Gregord406b032009-02-06 22:42:48 +00001688 return false;
1689 }
1690 }
1691
1692 return true;
1693}
1694
1695/// \brief Check whether a template can be declared within this scope.
1696///
1697/// If the template declaration is valid in this scope, returns
1698/// false. Otherwise, issues a diagnostic and returns true.
1699bool
1700Sema::CheckTemplateDeclScope(Scope *S,
1701 MultiTemplateParamsArg &TemplateParameterLists) {
1702 assert(TemplateParameterLists.size() > 0 && "Not a template");
1703
1704 // Find the nearest enclosing declaration scope.
1705 while ((S->getFlags() & Scope::DeclScope) == 0 ||
1706 (S->getFlags() & Scope::TemplateParamScope) != 0)
1707 S = S->getParent();
1708
1709 TemplateParameterList *TemplateParams =
1710 static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
1711 SourceLocation TemplateLoc = TemplateParams->getTemplateLoc();
1712 SourceRange TemplateRange
1713 = SourceRange(TemplateLoc, TemplateParams->getRAngleLoc());
1714
1715 // C++ [temp]p2:
1716 // A template-declaration can appear only as a namespace scope or
1717 // class scope declaration.
1718 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
1719 while (Ctx && isa<LinkageSpecDecl>(Ctx)) {
1720 if (cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
1721 return Diag(TemplateLoc, diag::err_template_linkage)
1722 << TemplateRange;
1723
1724 Ctx = Ctx->getParent();
1725 }
1726
1727 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
1728 return false;
1729
1730 return Diag(TemplateLoc, diag::err_template_outside_namespace_or_class_scope)
1731 << TemplateRange;
1732}
Douglas Gregora08b6c72009-02-17 23:15:12 +00001733
Douglas Gregor0d93f692009-02-25 22:02:03 +00001734/// \brief Check whether a class template specialization in the
1735/// current context is well-formed.
1736///
1737/// This routine determines whether a class template specialization
1738/// can be declared in the current context (C++ [temp.expl.spec]p2)
1739/// and emits appropriate diagnostics if there was an error. It
1740/// returns true if there was an error that we cannot recover from,
1741/// and false otherwise.
1742bool
1743Sema::CheckClassTemplateSpecializationScope(ClassTemplateDecl *ClassTemplate,
1744 ClassTemplateSpecializationDecl *PrevDecl,
1745 SourceLocation TemplateNameLoc,
1746 SourceRange ScopeSpecifierRange) {
1747 // C++ [temp.expl.spec]p2:
1748 // An explicit specialization shall be declared in the namespace
1749 // of which the template is a member, or, for member templates, in
1750 // the namespace of which the enclosing class or enclosing class
1751 // template is a member. An explicit specialization of a member
1752 // function, member class or static data member of a class
1753 // template shall be declared in the namespace of which the class
1754 // template is a member. Such a declaration may also be a
1755 // definition. If the declaration is not a definition, the
1756 // specialization may be defined later in the name- space in which
1757 // the explicit specialization was declared, or in a namespace
1758 // that encloses the one in which the explicit specialization was
1759 // declared.
1760 if (CurContext->getLookupContext()->isFunctionOrMethod()) {
1761 Diag(TemplateNameLoc, diag::err_template_spec_decl_function_scope)
1762 << ClassTemplate;
1763 return true;
1764 }
1765
1766 DeclContext *DC = CurContext->getEnclosingNamespaceContext();
1767 DeclContext *TemplateContext
1768 = ClassTemplate->getDeclContext()->getEnclosingNamespaceContext();
1769 if (!PrevDecl || PrevDecl->getSpecializationKind() == TSK_Undeclared) {
1770 // There is no prior declaration of this entity, so this
1771 // specialization must be in the same context as the template
1772 // itself.
1773 if (DC != TemplateContext) {
1774 if (isa<TranslationUnitDecl>(TemplateContext))
1775 Diag(TemplateNameLoc, diag::err_template_spec_decl_out_of_scope_global)
1776 << ClassTemplate << ScopeSpecifierRange;
1777 else if (isa<NamespaceDecl>(TemplateContext))
1778 Diag(TemplateNameLoc, diag::err_template_spec_decl_out_of_scope)
1779 << ClassTemplate << cast<NamedDecl>(TemplateContext)
1780 << ScopeSpecifierRange;
1781
1782 Diag(ClassTemplate->getLocation(), diag::note_template_decl_here);
1783 }
1784
1785 return false;
1786 }
1787
1788 // We have a previous declaration of this entity. Make sure that
1789 // this redeclaration (or definition) occurs in an enclosing namespace.
1790 if (!CurContext->Encloses(TemplateContext)) {
1791 if (isa<TranslationUnitDecl>(TemplateContext))
1792 Diag(TemplateNameLoc, diag::err_template_spec_redecl_global_scope)
1793 << ClassTemplate << ScopeSpecifierRange;
1794 else if (isa<NamespaceDecl>(TemplateContext))
1795 Diag(TemplateNameLoc, diag::err_template_spec_redecl_out_of_scope)
1796 << ClassTemplate << cast<NamedDecl>(TemplateContext)
1797 << ScopeSpecifierRange;
1798
1799 Diag(ClassTemplate->getLocation(), diag::note_template_decl_here);
1800 }
1801
1802 return false;
1803}
1804
Douglas Gregorc5d6fa72009-03-25 00:13:59 +00001805Sema::DeclResult
Douglas Gregora08b6c72009-02-17 23:15:12 +00001806Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec, TagKind TK,
1807 SourceLocation KWLoc,
1808 const CXXScopeSpec &SS,
Douglas Gregordd13e842009-03-30 22:58:21 +00001809 TemplateTy TemplateD,
Douglas Gregora08b6c72009-02-17 23:15:12 +00001810 SourceLocation TemplateNameLoc,
1811 SourceLocation LAngleLoc,
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001812 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregora08b6c72009-02-17 23:15:12 +00001813 SourceLocation *TemplateArgLocs,
1814 SourceLocation RAngleLoc,
1815 AttributeList *Attr,
1816 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregora08b6c72009-02-17 23:15:12 +00001817 // Find the class template we're specializing
Douglas Gregordd13e842009-03-30 22:58:21 +00001818 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Douglas Gregora08b6c72009-02-17 23:15:12 +00001819 ClassTemplateDecl *ClassTemplate
Douglas Gregordd13e842009-03-30 22:58:21 +00001820 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
Douglas Gregora08b6c72009-02-17 23:15:12 +00001821
Douglas Gregor0d93f692009-02-25 22:02:03 +00001822 // Check the validity of the template headers that introduce this
1823 // template.
Douglas Gregor50113ca2009-02-25 22:18:32 +00001824 // FIXME: Once we have member templates, we'll need to check
1825 // C++ [temp.expl.spec]p17-18, where we could have multiple levels of
1826 // template<> headers.
Douglas Gregor3bb30002009-02-26 21:00:50 +00001827 if (TemplateParameterLists.size() == 0)
1828 Diag(KWLoc, diag::err_template_spec_needs_header)
Douglas Gregor61be3602009-02-27 17:53:17 +00001829 << CodeModificationHint::CreateInsertion(KWLoc, "template<> ");
Douglas Gregor3bb30002009-02-26 21:00:50 +00001830 else {
Douglas Gregor0d93f692009-02-25 22:02:03 +00001831 TemplateParameterList *TemplateParams
1832 = static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
Chris Lattner5261d0c2009-03-28 19:18:32 +00001833 if (TemplateParameterLists.size() > 1) {
1834 Diag(TemplateParams->getTemplateLoc(),
1835 diag::err_template_spec_extra_headers);
1836 return true;
1837 }
Douglas Gregor0d93f692009-02-25 22:02:03 +00001838
Chris Lattner5261d0c2009-03-28 19:18:32 +00001839 if (TemplateParams->size() > 0) {
Douglas Gregor0d93f692009-02-25 22:02:03 +00001840 // FIXME: No support for class template partial specialization.
Chris Lattner5261d0c2009-03-28 19:18:32 +00001841 Diag(TemplateParams->getTemplateLoc(), diag::unsup_template_partial_spec);
1842 return true;
1843 }
Douglas Gregor0d93f692009-02-25 22:02:03 +00001844 }
1845
Douglas Gregora08b6c72009-02-17 23:15:12 +00001846 // Check that the specialization uses the same tag kind as the
1847 // original template.
1848 TagDecl::TagKind Kind;
1849 switch (TagSpec) {
1850 default: assert(0 && "Unknown tag type!");
1851 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
1852 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
1853 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
1854 }
1855 if (ClassTemplate->getTemplatedDecl()->getTagKind() != Kind) {
1856 Diag(KWLoc, diag::err_use_with_wrong_tag) << ClassTemplate;
1857 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
1858 diag::note_previous_use);
1859 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
1860 }
1861
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001862 // Translate the parser's template argument list in our AST format.
1863 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
1864 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
1865
Douglas Gregora08b6c72009-02-17 23:15:12 +00001866 // Check that the template argument list is well-formed for this
1867 // template.
1868 llvm::SmallVector<TemplateArgument, 16> ConvertedTemplateArgs;
1869 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001870 &TemplateArgs[0], TemplateArgs.size(),
1871 RAngleLoc, ConvertedTemplateArgs))
Douglas Gregorc5d6fa72009-03-25 00:13:59 +00001872 return true;
Douglas Gregora08b6c72009-02-17 23:15:12 +00001873
1874 assert((ConvertedTemplateArgs.size() ==
1875 ClassTemplate->getTemplateParameters()->size()) &&
1876 "Converted template argument list is too short!");
1877
1878 // Find the class template specialization declaration that
1879 // corresponds to these arguments.
1880 llvm::FoldingSetNodeID ID;
1881 ClassTemplateSpecializationDecl::Profile(ID, &ConvertedTemplateArgs[0],
1882 ConvertedTemplateArgs.size());
1883 void *InsertPos = 0;
1884 ClassTemplateSpecializationDecl *PrevDecl
1885 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
1886
1887 ClassTemplateSpecializationDecl *Specialization = 0;
1888
Douglas Gregor0d93f692009-02-25 22:02:03 +00001889 // Check whether we can declare a class template specialization in
1890 // the current scope.
1891 if (CheckClassTemplateSpecializationScope(ClassTemplate, PrevDecl,
1892 TemplateNameLoc,
1893 SS.getRange()))
Douglas Gregorc5d6fa72009-03-25 00:13:59 +00001894 return true;
Douglas Gregor0d93f692009-02-25 22:02:03 +00001895
Douglas Gregora08b6c72009-02-17 23:15:12 +00001896 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
1897 // Since the only prior class template specialization with these
1898 // arguments was referenced but not declared, reuse that
1899 // declaration node as our own, updating its source location to
1900 // reflect our new declaration.
Douglas Gregora08b6c72009-02-17 23:15:12 +00001901 Specialization = PrevDecl;
Douglas Gregor50113ca2009-02-25 22:18:32 +00001902 Specialization->setLocation(TemplateNameLoc);
Douglas Gregora08b6c72009-02-17 23:15:12 +00001903 PrevDecl = 0;
1904 } else {
1905 // Create a new class template specialization declaration node for
1906 // this explicit specialization.
1907 Specialization
1908 = ClassTemplateSpecializationDecl::Create(Context,
1909 ClassTemplate->getDeclContext(),
1910 TemplateNameLoc,
1911 ClassTemplate,
1912 &ConvertedTemplateArgs[0],
1913 ConvertedTemplateArgs.size(),
1914 PrevDecl);
1915
1916 if (PrevDecl) {
1917 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
1918 ClassTemplate->getSpecializations().GetOrInsertNode(Specialization);
1919 } else {
1920 ClassTemplate->getSpecializations().InsertNode(Specialization,
1921 InsertPos);
1922 }
1923 }
1924
1925 // Note that this is an explicit specialization.
1926 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
1927
1928 // Check that this isn't a redefinition of this specialization.
1929 if (TK == TK_Definition) {
1930 if (RecordDecl *Def = Specialization->getDefinition(Context)) {
1931 // FIXME: Should also handle explicit specialization after
1932 // implicit instantiation with a special diagnostic.
1933 SourceRange Range(TemplateNameLoc, RAngleLoc);
1934 Diag(TemplateNameLoc, diag::err_redefinition)
1935 << Specialization << Range;
1936 Diag(Def->getLocation(), diag::note_previous_definition);
1937 Specialization->setInvalidDecl();
Douglas Gregorc5d6fa72009-03-25 00:13:59 +00001938 return true;
Douglas Gregora08b6c72009-02-17 23:15:12 +00001939 }
1940 }
1941
Douglas Gregor9c7825b2009-02-26 22:19:44 +00001942 // Build the fully-sugared type for this class template
1943 // specialization as the user wrote in the specialization
1944 // itself. This means that we'll pretty-print the type retrieved
1945 // from the specialization's declaration the way that the user
1946 // actually wrote the specialization, rather than formatting the
1947 // name based on the "canonical" representation used to store the
1948 // template arguments in the specialization.
Douglas Gregor8c795a12009-03-19 00:39:20 +00001949 QualType WrittenTy
Douglas Gregordd13e842009-03-30 22:58:21 +00001950 = Context.getTemplateSpecializationType(Name,
1951 &TemplateArgs[0],
1952 TemplateArgs.size(),
Douglas Gregor8c795a12009-03-19 00:39:20 +00001953 Context.getTypeDeclType(Specialization));
Douglas Gregordd13e842009-03-30 22:58:21 +00001954 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001955 TemplateArgsIn.release();
Douglas Gregora08b6c72009-02-17 23:15:12 +00001956
Douglas Gregor50113ca2009-02-25 22:18:32 +00001957 // C++ [temp.expl.spec]p9:
1958 // A template explicit specialization is in the scope of the
1959 // namespace in which the template was defined.
1960 //
1961 // We actually implement this paragraph where we set the semantic
1962 // context (in the creation of the ClassTemplateSpecializationDecl),
1963 // but we also maintain the lexical context where the actual
1964 // definition occurs.
Douglas Gregora08b6c72009-02-17 23:15:12 +00001965 Specialization->setLexicalDeclContext(CurContext);
1966
1967 // We may be starting the definition of this specialization.
1968 if (TK == TK_Definition)
1969 Specialization->startDefinition();
1970
1971 // Add the specialization into its lexical context, so that it can
1972 // be seen when iterating through the list of declarations in that
1973 // context. However, specializations are not found by name lookup.
1974 CurContext->addDecl(Specialization);
Chris Lattner5261d0c2009-03-28 19:18:32 +00001975 return DeclPtrTy::make(Specialization);
Douglas Gregora08b6c72009-02-17 23:15:12 +00001976}
Douglas Gregord3022602009-03-27 23:10:48 +00001977
1978Sema::TypeResult
1979Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
1980 const IdentifierInfo &II, SourceLocation IdLoc) {
1981 NestedNameSpecifier *NNS
1982 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
1983 if (!NNS)
1984 return true;
1985
1986 QualType T = CheckTypenameType(NNS, II, SourceRange(TypenameLoc, IdLoc));
Douglas Gregord3022602009-03-27 23:10:48 +00001987 return T.getAsOpaquePtr();
1988}
1989
1990/// \brief Build the type that describes a C++ typename specifier,
1991/// e.g., "typename T::type".
1992QualType
1993Sema::CheckTypenameType(NestedNameSpecifier *NNS, const IdentifierInfo &II,
1994 SourceRange Range) {
1995 if (NNS->isDependent()) // FIXME: member of the current instantiation!
1996 return Context.getTypenameType(NNS, &II);
1997
1998 CXXScopeSpec SS;
1999 SS.setScopeRep(NNS);
2000 SS.setRange(Range);
2001 if (RequireCompleteDeclContext(SS))
2002 return QualType();
2003
2004 DeclContext *Ctx = computeDeclContext(SS);
2005 assert(Ctx && "No declaration context?");
2006
2007 DeclarationName Name(&II);
2008 LookupResult Result = LookupQualifiedName(Ctx, Name, LookupOrdinaryName,
2009 false);
2010 unsigned DiagID = 0;
2011 Decl *Referenced = 0;
2012 switch (Result.getKind()) {
2013 case LookupResult::NotFound:
2014 if (Ctx->isTranslationUnit())
2015 DiagID = diag::err_typename_nested_not_found_global;
2016 else
2017 DiagID = diag::err_typename_nested_not_found;
2018 break;
2019
2020 case LookupResult::Found:
2021 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getAsDecl())) {
2022 // We found a type. Build a QualifiedNameType, since the
2023 // typename-specifier was just sugar. FIXME: Tell
2024 // QualifiedNameType that it has a "typename" prefix.
2025 return Context.getQualifiedNameType(NNS, Context.getTypeDeclType(Type));
2026 }
2027
2028 DiagID = diag::err_typename_nested_not_type;
2029 Referenced = Result.getAsDecl();
2030 break;
2031
2032 case LookupResult::FoundOverloaded:
2033 DiagID = diag::err_typename_nested_not_type;
2034 Referenced = *Result.begin();
2035 break;
2036
2037 case LookupResult::AmbiguousBaseSubobjectTypes:
2038 case LookupResult::AmbiguousBaseSubobjects:
2039 case LookupResult::AmbiguousReference:
2040 DiagnoseAmbiguousLookup(Result, Name, Range.getEnd(), Range);
2041 return QualType();
2042 }
2043
2044 // If we get here, it's because name lookup did not find a
2045 // type. Emit an appropriate diagnostic and return an error.
2046 if (NamedDecl *NamedCtx = dyn_cast<NamedDecl>(Ctx))
2047 Diag(Range.getEnd(), DiagID) << Range << Name << NamedCtx;
2048 else
2049 Diag(Range.getEnd(), DiagID) << Range << Name;
2050 if (Referenced)
2051 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
2052 << Name;
2053 return QualType();
2054}