blob: 5db19a59ac48d79c869586d6af7913ebca735096 [file] [log] [blame]
Douglas Gregordd861062008-12-05 18:15:24 +00001//===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===/
2
3//
4// The LLVM Compiler Infrastructure
5//
6// This file is distributed under the University of Illinois Open Source
7// License. See LICENSE.TXT for details.
Douglas Gregor74296542009-02-27 19:31:52 +00008//===----------------------------------------------------------------------===/
Douglas Gregordd861062008-12-05 18:15:24 +00009
10//
11// This file implements semantic analysis for C++ templates.
Douglas Gregor74296542009-02-27 19:31:52 +000012//===----------------------------------------------------------------------===/
Douglas Gregordd861062008-12-05 18:15:24 +000013
14#include "Sema.h"
Douglas Gregord406b032009-02-06 22:42:48 +000015#include "clang/AST/ASTContext.h"
Douglas Gregor1b21c7f2008-12-05 23:32:09 +000016#include "clang/AST/Expr.h"
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +000017#include "clang/AST/ExprCXX.h"
Douglas Gregor279272e2009-02-04 19:02:06 +000018#include "clang/AST/DeclTemplate.h"
Douglas Gregordd861062008-12-05 18:15:24 +000019#include "clang/Parse/DeclSpec.h"
20#include "clang/Basic/LangOptions.h"
21
22using namespace clang;
23
Douglas Gregor2fa10442008-12-18 19:37:40 +000024/// isTemplateName - Determines whether the identifier II is a
25/// template name in the current scope, and returns the template
26/// declaration if II names a template. An optional CXXScope can be
27/// passed to indicate the C++ scope in which the identifier will be
28/// found.
Douglas Gregoraabb8502009-03-31 00:43:58 +000029TemplateNameKind Sema::isTemplateName(const IdentifierInfo &II, Scope *S,
Douglas Gregordd13e842009-03-30 22:58:21 +000030 TemplateTy &TemplateResult,
Douglas Gregor0c281a82009-02-25 19:37:18 +000031 const CXXScopeSpec *SS) {
Douglas Gregor09be81b2009-02-04 17:27:36 +000032 NamedDecl *IIDecl = LookupParsedName(S, SS, &II, LookupOrdinaryName);
Douglas Gregor2fa10442008-12-18 19:37:40 +000033
Douglas Gregordd13e842009-03-30 22:58:21 +000034 TemplateNameKind TNK = TNK_Non_template;
35 TemplateDecl *Template = 0;
36
Douglas Gregor2fa10442008-12-18 19:37:40 +000037 if (IIDecl) {
Douglas Gregordd13e842009-03-30 22:58:21 +000038 if ((Template = dyn_cast<TemplateDecl>(IIDecl))) {
Douglas Gregor8e458f42009-02-09 18:46:07 +000039 if (isa<FunctionTemplateDecl>(IIDecl))
Douglas Gregordd13e842009-03-30 22:58:21 +000040 TNK = TNK_Function_template;
Douglas Gregoraabb8502009-03-31 00:43:58 +000041 else if (isa<ClassTemplateDecl>(IIDecl) ||
42 isa<TemplateTemplateParmDecl>(IIDecl))
43 TNK = TNK_Type_template;
Douglas Gregordd13e842009-03-30 22:58:21 +000044 else
45 assert(false && "Unknown template declaration kind");
Douglas Gregor55216ac2009-03-26 00:10:35 +000046 } else if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(IIDecl)) {
47 // C++ [temp.local]p1:
48 // Like normal (non-template) classes, class templates have an
49 // injected-class-name (Clause 9). The injected-class-name
50 // can be used with or without a template-argument-list. When
51 // it is used without a template-argument-list, it is
52 // equivalent to the injected-class-name followed by the
53 // template-parameters of the class template enclosed in
54 // <>. When it is used with a template-argument-list, it
55 // refers to the specified class template specialization,
56 // which could be the current specialization or another
57 // specialization.
58 if (Record->isInjectedClassName()) {
59 Record = cast<CXXRecordDecl>(Context.getCanonicalDecl(Record));
Douglas Gregordd13e842009-03-30 22:58:21 +000060 if ((Template = Record->getDescribedClassTemplate()))
Douglas Gregoraabb8502009-03-31 00:43:58 +000061 TNK = TNK_Type_template;
Douglas Gregordd13e842009-03-30 22:58:21 +000062 else if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor55216ac2009-03-26 00:10:35 +000063 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
Douglas Gregordd13e842009-03-30 22:58:21 +000064 Template = Spec->getSpecializedTemplate();
Douglas Gregoraabb8502009-03-31 00:43:58 +000065 TNK = TNK_Type_template;
Douglas Gregor55216ac2009-03-26 00:10:35 +000066 }
67 }
Douglas Gregor8e458f42009-02-09 18:46:07 +000068 }
Douglas Gregor279272e2009-02-04 19:02:06 +000069
Douglas Gregor8e458f42009-02-09 18:46:07 +000070 // FIXME: What follows is a gross hack.
Douglas Gregor2fa10442008-12-18 19:37:40 +000071 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(IIDecl)) {
Douglas Gregor8e458f42009-02-09 18:46:07 +000072 if (FD->getType()->isDependentType()) {
Douglas Gregordd13e842009-03-30 22:58:21 +000073 TemplateResult = TemplateTy::make(FD);
Douglas Gregor8e458f42009-02-09 18:46:07 +000074 return TNK_Function_template;
75 }
Douglas Gregor2fa10442008-12-18 19:37:40 +000076 } else if (OverloadedFunctionDecl *Ovl
77 = dyn_cast<OverloadedFunctionDecl>(IIDecl)) {
78 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
79 FEnd = Ovl->function_end();
80 F != FEnd; ++F) {
Douglas Gregor8e458f42009-02-09 18:46:07 +000081 if ((*F)->getType()->isDependentType()) {
Douglas Gregordd13e842009-03-30 22:58:21 +000082 TemplateResult = TemplateTy::make(Ovl);
Douglas Gregor8e458f42009-02-09 18:46:07 +000083 return TNK_Function_template;
84 }
Douglas Gregor2fa10442008-12-18 19:37:40 +000085 }
86 }
Douglas Gregordd13e842009-03-30 22:58:21 +000087
88 if (TNK != TNK_Non_template) {
89 if (SS && SS->isSet() && !SS->isInvalid()) {
90 NestedNameSpecifier *Qualifier
91 = static_cast<NestedNameSpecifier *>(SS->getScopeRep());
92 TemplateResult
93 = TemplateTy::make(Context.getQualifiedTemplateName(Qualifier,
94 false,
95 Template));
96 } else
97 TemplateResult = TemplateTy::make(TemplateName(Template));
98 }
Douglas Gregor2fa10442008-12-18 19:37:40 +000099 }
Douglas Gregordd13e842009-03-30 22:58:21 +0000100 return TNK;
Douglas Gregor2fa10442008-12-18 19:37:40 +0000101}
102
Douglas Gregordd861062008-12-05 18:15:24 +0000103/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
104/// that the template parameter 'PrevDecl' is being shadowed by a new
105/// declaration at location Loc. Returns true to indicate that this is
106/// an error, and false otherwise.
107bool Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
Douglas Gregor2715a1f2008-12-08 18:40:42 +0000108 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregordd861062008-12-05 18:15:24 +0000109
110 // Microsoft Visual C++ permits template parameters to be shadowed.
111 if (getLangOptions().Microsoft)
112 return false;
113
114 // C++ [temp.local]p4:
115 // A template-parameter shall not be redeclared within its
116 // scope (including nested scopes).
117 Diag(Loc, diag::err_template_param_shadow)
118 << cast<NamedDecl>(PrevDecl)->getDeclName();
119 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
120 return true;
121}
122
Douglas Gregored3a3982009-03-03 04:44:36 +0000123/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregor279272e2009-02-04 19:02:06 +0000124/// the parameter D to reference the templated declaration and return a pointer
125/// to the template declaration. Otherwise, do nothing to D and return null.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000126TemplateDecl *Sema::AdjustDeclIfTemplate(DeclPtrTy &D) {
127 if (TemplateDecl *Temp = dyn_cast<TemplateDecl>(D.getAs<Decl>())) {
128 D = DeclPtrTy::make(Temp->getTemplatedDecl());
Douglas Gregor279272e2009-02-04 19:02:06 +0000129 return Temp;
130 }
131 return 0;
132}
133
Douglas Gregordd861062008-12-05 18:15:24 +0000134/// ActOnTypeParameter - Called when a C++ template type parameter
135/// (e.g., "typename T") has been parsed. Typename specifies whether
136/// the keyword "typename" was used to declare the type parameter
137/// (otherwise, "class" was used), and KeyLoc is the location of the
138/// "class" or "typename" keyword. ParamName is the name of the
139/// parameter (NULL indicates an unnamed template parameter) and
140/// ParamName is the location of the parameter name (if any).
141/// If the type parameter has a default argument, it will be added
142/// later via ActOnTypeParameterDefault.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000143Sema::DeclPtrTy Sema::ActOnTypeParameter(Scope *S, bool Typename,
144 SourceLocation KeyLoc,
145 IdentifierInfo *ParamName,
146 SourceLocation ParamNameLoc,
147 unsigned Depth, unsigned Position) {
Douglas Gregordd861062008-12-05 18:15:24 +0000148 assert(S->isTemplateParamScope() &&
149 "Template type parameter not in template parameter scope!");
150 bool Invalid = false;
151
152 if (ParamName) {
Douglas Gregor09be81b2009-02-04 17:27:36 +0000153 NamedDecl *PrevDecl = LookupName(S, ParamName, LookupTagName);
Douglas Gregor2715a1f2008-12-08 18:40:42 +0000154 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregordd861062008-12-05 18:15:24 +0000155 Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc,
156 PrevDecl);
157 }
158
Douglas Gregord406b032009-02-06 22:42:48 +0000159 SourceLocation Loc = ParamNameLoc;
160 if (!ParamName)
161 Loc = KeyLoc;
162
Douglas Gregordd861062008-12-05 18:15:24 +0000163 TemplateTypeParmDecl *Param
Douglas Gregord406b032009-02-06 22:42:48 +0000164 = TemplateTypeParmDecl::Create(Context, CurContext, Loc,
Douglas Gregor279272e2009-02-04 19:02:06 +0000165 Depth, Position, ParamName, Typename);
Douglas Gregordd861062008-12-05 18:15:24 +0000166 if (Invalid)
167 Param->setInvalidDecl();
168
169 if (ParamName) {
170 // Add the template parameter into the current scope.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000171 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregordd861062008-12-05 18:15:24 +0000172 IdResolver.AddDecl(Param);
173 }
174
Chris Lattner5261d0c2009-03-28 19:18:32 +0000175 return DeclPtrTy::make(Param);
Douglas Gregordd861062008-12-05 18:15:24 +0000176}
177
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000178/// ActOnTypeParameterDefault - Adds a default argument (the type
179/// Default) to the given template type parameter (TypeParam).
Chris Lattner5261d0c2009-03-28 19:18:32 +0000180void Sema::ActOnTypeParameterDefault(DeclPtrTy TypeParam,
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000181 SourceLocation EqualLoc,
182 SourceLocation DefaultLoc,
183 TypeTy *DefaultT) {
184 TemplateTypeParmDecl *Parm
Chris Lattner5261d0c2009-03-28 19:18:32 +0000185 = cast<TemplateTypeParmDecl>(TypeParam.getAs<Decl>());
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000186 QualType Default = QualType::getFromOpaquePtr(DefaultT);
187
188 // C++ [temp.param]p14:
189 // A template-parameter shall not be used in its own default argument.
190 // FIXME: Implement this check! Needs a recursive walk over the types.
191
192 // Check the template argument itself.
193 if (CheckTemplateArgument(Parm, Default, DefaultLoc)) {
194 Parm->setInvalidDecl();
195 return;
196 }
197
198 Parm->setDefaultArgument(Default, DefaultLoc, false);
199}
200
Douglas Gregored3a3982009-03-03 04:44:36 +0000201/// \brief Check that the type of a non-type template parameter is
202/// well-formed.
203///
204/// \returns the (possibly-promoted) parameter type if valid;
205/// otherwise, produces a diagnostic and returns a NULL type.
206QualType
207Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
208 // C++ [temp.param]p4:
209 //
210 // A non-type template-parameter shall have one of the following
211 // (optionally cv-qualified) types:
212 //
213 // -- integral or enumeration type,
214 if (T->isIntegralType() || T->isEnumeralType() ||
215 // -- pointer to object or pointer to function,
216 (T->isPointerType() &&
217 (T->getAsPointerType()->getPointeeType()->isObjectType() ||
218 T->getAsPointerType()->getPointeeType()->isFunctionType())) ||
219 // -- reference to object or reference to function,
220 T->isReferenceType() ||
221 // -- pointer to member.
222 T->isMemberPointerType() ||
223 // If T is a dependent type, we can't do the check now, so we
224 // assume that it is well-formed.
225 T->isDependentType())
226 return T;
227 // C++ [temp.param]p8:
228 //
229 // A non-type template-parameter of type "array of T" or
230 // "function returning T" is adjusted to be of type "pointer to
231 // T" or "pointer to function returning T", respectively.
232 else if (T->isArrayType())
233 // FIXME: Keep the type prior to promotion?
234 return Context.getArrayDecayedType(T);
235 else if (T->isFunctionType())
236 // FIXME: Keep the type prior to promotion?
237 return Context.getPointerType(T);
238
239 Diag(Loc, diag::err_template_nontype_parm_bad_type)
240 << T;
241
242 return QualType();
243}
244
Douglas Gregordd861062008-12-05 18:15:24 +0000245/// ActOnNonTypeTemplateParameter - Called when a C++ non-type
246/// template parameter (e.g., "int Size" in "template<int Size>
247/// class Array") has been parsed. S is the current scope and D is
248/// the parsed declarator.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000249Sema::DeclPtrTy Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
250 unsigned Depth,
251 unsigned Position) {
Douglas Gregordd861062008-12-05 18:15:24 +0000252 QualType T = GetTypeForDeclarator(D, S);
253
Douglas Gregor279272e2009-02-04 19:02:06 +0000254 assert(S->isTemplateParamScope() &&
255 "Non-type template parameter not in template parameter scope!");
Douglas Gregordd861062008-12-05 18:15:24 +0000256 bool Invalid = false;
257
258 IdentifierInfo *ParamName = D.getIdentifier();
259 if (ParamName) {
Douglas Gregor09be81b2009-02-04 17:27:36 +0000260 NamedDecl *PrevDecl = LookupName(S, ParamName, LookupTagName);
Douglas Gregor2715a1f2008-12-08 18:40:42 +0000261 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregordd861062008-12-05 18:15:24 +0000262 Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
Douglas Gregor279272e2009-02-04 19:02:06 +0000263 PrevDecl);
Douglas Gregordd861062008-12-05 18:15:24 +0000264 }
265
Douglas Gregored3a3982009-03-03 04:44:36 +0000266 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
Douglas Gregor8b90e8e2009-03-09 16:46:39 +0000267 if (T.isNull()) {
Douglas Gregored3a3982009-03-03 04:44:36 +0000268 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregor8b90e8e2009-03-09 16:46:39 +0000269 Invalid = true;
270 }
Douglas Gregor62cdc792009-02-10 17:43:50 +0000271
Douglas Gregordd861062008-12-05 18:15:24 +0000272 NonTypeTemplateParmDecl *Param
273 = NonTypeTemplateParmDecl::Create(Context, CurContext, D.getIdentifierLoc(),
Douglas Gregor279272e2009-02-04 19:02:06 +0000274 Depth, Position, ParamName, T);
Douglas Gregordd861062008-12-05 18:15:24 +0000275 if (Invalid)
276 Param->setInvalidDecl();
277
278 if (D.getIdentifier()) {
279 // Add the template parameter into the current scope.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000280 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregordd861062008-12-05 18:15:24 +0000281 IdResolver.AddDecl(Param);
282 }
Chris Lattner5261d0c2009-03-28 19:18:32 +0000283 return DeclPtrTy::make(Param);
Douglas Gregordd861062008-12-05 18:15:24 +0000284}
Douglas Gregor52473432008-12-24 02:52:09 +0000285
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000286/// \brief Adds a default argument to the given non-type template
287/// parameter.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000288void Sema::ActOnNonTypeTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000289 SourceLocation EqualLoc,
290 ExprArg DefaultE) {
291 NonTypeTemplateParmDecl *TemplateParm
Chris Lattner5261d0c2009-03-28 19:18:32 +0000292 = cast<NonTypeTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000293 Expr *Default = static_cast<Expr *>(DefaultE.get());
294
295 // C++ [temp.param]p14:
296 // A template-parameter shall not be used in its own default argument.
297 // FIXME: Implement this check! Needs a recursive walk over the types.
298
299 // Check the well-formedness of the default template argument.
Douglas Gregored3a3982009-03-03 04:44:36 +0000300 if (CheckTemplateArgument(TemplateParm, TemplateParm->getType(), Default)) {
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000301 TemplateParm->setInvalidDecl();
302 return;
303 }
304
305 TemplateParm->setDefaultArgument(static_cast<Expr *>(DefaultE.release()));
306}
307
Douglas Gregor279272e2009-02-04 19:02:06 +0000308
309/// ActOnTemplateTemplateParameter - Called when a C++ template template
310/// parameter (e.g. T in template <template <typename> class T> class array)
311/// has been parsed. S is the current scope.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000312Sema::DeclPtrTy Sema::ActOnTemplateTemplateParameter(Scope* S,
313 SourceLocation TmpLoc,
314 TemplateParamsTy *Params,
315 IdentifierInfo *Name,
316 SourceLocation NameLoc,
317 unsigned Depth,
318 unsigned Position)
Douglas Gregor279272e2009-02-04 19:02:06 +0000319{
320 assert(S->isTemplateParamScope() &&
321 "Template template parameter not in template parameter scope!");
322
323 // Construct the parameter object.
324 TemplateTemplateParmDecl *Param =
325 TemplateTemplateParmDecl::Create(Context, CurContext, TmpLoc, Depth,
326 Position, Name,
327 (TemplateParameterList*)Params);
328
329 // Make sure the parameter is valid.
330 // FIXME: Decl object is not currently invalidated anywhere so this doesn't
331 // do anything yet. However, if the template parameter list or (eventual)
332 // default value is ever invalidated, that will propagate here.
333 bool Invalid = false;
334 if (Invalid) {
335 Param->setInvalidDecl();
336 }
337
338 // If the tt-param has a name, then link the identifier into the scope
339 // and lookup mechanisms.
340 if (Name) {
Chris Lattner5261d0c2009-03-28 19:18:32 +0000341 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor279272e2009-02-04 19:02:06 +0000342 IdResolver.AddDecl(Param);
343 }
344
Chris Lattner5261d0c2009-03-28 19:18:32 +0000345 return DeclPtrTy::make(Param);
Douglas Gregor279272e2009-02-04 19:02:06 +0000346}
347
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000348/// \brief Adds a default argument to the given template template
349/// parameter.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000350void Sema::ActOnTemplateTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000351 SourceLocation EqualLoc,
352 ExprArg DefaultE) {
353 TemplateTemplateParmDecl *TemplateParm
Chris Lattner5261d0c2009-03-28 19:18:32 +0000354 = cast<TemplateTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000355
356 // Since a template-template parameter's default argument is an
357 // id-expression, it must be a DeclRefExpr.
358 DeclRefExpr *Default
359 = cast<DeclRefExpr>(static_cast<Expr *>(DefaultE.get()));
360
361 // C++ [temp.param]p14:
362 // A template-parameter shall not be used in its own default argument.
363 // FIXME: Implement this check! Needs a recursive walk over the types.
364
365 // Check the well-formedness of the template argument.
366 if (!isa<TemplateDecl>(Default->getDecl())) {
367 Diag(Default->getSourceRange().getBegin(),
368 diag::err_template_arg_must_be_template)
369 << Default->getSourceRange();
370 TemplateParm->setInvalidDecl();
371 return;
372 }
373 if (CheckTemplateArgument(TemplateParm, Default)) {
374 TemplateParm->setInvalidDecl();
375 return;
376 }
377
378 DefaultE.release();
379 TemplateParm->setDefaultArgument(Default);
380}
381
Douglas Gregor52473432008-12-24 02:52:09 +0000382/// ActOnTemplateParameterList - Builds a TemplateParameterList that
383/// contains the template parameters in Params/NumParams.
384Sema::TemplateParamsTy *
385Sema::ActOnTemplateParameterList(unsigned Depth,
386 SourceLocation ExportLoc,
387 SourceLocation TemplateLoc,
388 SourceLocation LAngleLoc,
Chris Lattner5261d0c2009-03-28 19:18:32 +0000389 DeclPtrTy *Params, unsigned NumParams,
Douglas Gregor52473432008-12-24 02:52:09 +0000390 SourceLocation RAngleLoc) {
391 if (ExportLoc.isValid())
392 Diag(ExportLoc, diag::note_template_export_unsupported);
393
Douglas Gregord406b032009-02-06 22:42:48 +0000394 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
395 (Decl**)Params, NumParams, RAngleLoc);
Douglas Gregor52473432008-12-24 02:52:09 +0000396}
Douglas Gregor279272e2009-02-04 19:02:06 +0000397
Douglas Gregorc5d6fa72009-03-25 00:13:59 +0000398Sema::DeclResult
Douglas Gregord406b032009-02-06 22:42:48 +0000399Sema::ActOnClassTemplate(Scope *S, unsigned TagSpec, TagKind TK,
400 SourceLocation KWLoc, const CXXScopeSpec &SS,
401 IdentifierInfo *Name, SourceLocation NameLoc,
402 AttributeList *Attr,
Anders Carlssoned20fb92009-03-26 00:52:18 +0000403 MultiTemplateParamsArg TemplateParameterLists,
404 AccessSpecifier AS) {
Douglas Gregord406b032009-02-06 22:42:48 +0000405 assert(TemplateParameterLists.size() > 0 && "No template parameter lists?");
406 assert(TK != TK_Reference && "Can only declare or define class templates");
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000407 bool Invalid = false;
Douglas Gregord406b032009-02-06 22:42:48 +0000408
409 // Check that we can declare a template here.
410 if (CheckTemplateDeclScope(S, TemplateParameterLists))
Douglas Gregorc5d6fa72009-03-25 00:13:59 +0000411 return true;
Douglas Gregord406b032009-02-06 22:42:48 +0000412
413 TagDecl::TagKind Kind;
414 switch (TagSpec) {
415 default: assert(0 && "Unknown tag type!");
416 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
417 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
418 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
419 }
420
421 // There is no such thing as an unnamed class template.
422 if (!Name) {
423 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregorc5d6fa72009-03-25 00:13:59 +0000424 return true;
Douglas Gregord406b032009-02-06 22:42:48 +0000425 }
426
427 // Find any previous declaration with this name.
428 LookupResult Previous = LookupParsedName(S, &SS, Name, LookupOrdinaryName,
429 true);
430 assert(!Previous.isAmbiguous() && "Ambiguity in class template redecl?");
431 NamedDecl *PrevDecl = 0;
432 if (Previous.begin() != Previous.end())
433 PrevDecl = *Previous.begin();
434
435 DeclContext *SemanticContext = CurContext;
436 if (SS.isNotEmpty() && !SS.isInvalid()) {
Douglas Gregor734b4ba2009-03-19 00:18:19 +0000437 SemanticContext = computeDeclContext(SS);
Douglas Gregord406b032009-02-06 22:42:48 +0000438
439 // FIXME: need to match up several levels of template parameter
440 // lists here.
441 }
442
443 // FIXME: member templates!
444 TemplateParameterList *TemplateParams
445 = static_cast<TemplateParameterList *>(*TemplateParameterLists.release());
446
447 // If there is a previous declaration with the same name, check
448 // whether this is a valid redeclaration.
449 ClassTemplateDecl *PrevClassTemplate
450 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
451 if (PrevClassTemplate) {
452 // Ensure that the template parameter lists are compatible.
453 if (!TemplateParameterListsAreEqual(TemplateParams,
454 PrevClassTemplate->getTemplateParameters(),
455 /*Complain=*/true))
Douglas Gregorc5d6fa72009-03-25 00:13:59 +0000456 return true;
Douglas Gregord406b032009-02-06 22:42:48 +0000457
458 // C++ [temp.class]p4:
459 // In a redeclaration, partial specialization, explicit
460 // specialization or explicit instantiation of a class template,
461 // the class-key shall agree in kind with the original class
462 // template declaration (7.1.5.3).
463 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
464 if (PrevRecordDecl->getTagKind() != Kind) {
465 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
466 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregorc5d6fa72009-03-25 00:13:59 +0000467 return true;
Douglas Gregord406b032009-02-06 22:42:48 +0000468 }
469
470
471 // Check for redefinition of this class template.
472 if (TK == TK_Definition) {
473 if (TagDecl *Def = PrevRecordDecl->getDefinition(Context)) {
474 Diag(NameLoc, diag::err_redefinition) << Name;
475 Diag(Def->getLocation(), diag::note_previous_definition);
476 // FIXME: Would it make sense to try to "forget" the previous
477 // definition, as part of error recovery?
Douglas Gregorc5d6fa72009-03-25 00:13:59 +0000478 return true;
Douglas Gregord406b032009-02-06 22:42:48 +0000479 }
480 }
481 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
482 // Maybe we will complain about the shadowed template parameter.
483 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
484 // Just pretend that we didn't see the previous declaration.
485 PrevDecl = 0;
486 } else if (PrevDecl) {
487 // C++ [temp]p5:
488 // A class template shall not have the same name as any other
489 // template, class, function, object, enumeration, enumerator,
490 // namespace, or type in the same scope (3.3), except as specified
491 // in (14.5.4).
492 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
493 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregorc5d6fa72009-03-25 00:13:59 +0000494 return true;
Douglas Gregord406b032009-02-06 22:42:48 +0000495 }
496
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000497 // Check the template parameter list of this declaration, possibly
498 // merging in the template parameter list from the previous class
499 // template declaration.
500 if (CheckTemplateParameterList(TemplateParams,
501 PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0))
502 Invalid = true;
503
Douglas Gregord406b032009-02-06 22:42:48 +0000504 // If we had a scope specifier, we better have a previous template
505 // declaration!
506
Douglas Gregor55216ac2009-03-26 00:10:35 +0000507 CXXRecordDecl *NewClass =
Douglas Gregord406b032009-02-06 22:42:48 +0000508 CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name,
509 PrevClassTemplate?
510 PrevClassTemplate->getTemplatedDecl() : 0);
511
512 ClassTemplateDecl *NewTemplate
513 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
514 DeclarationName(Name), TemplateParams,
Douglas Gregor47bde7c2009-03-19 17:26:29 +0000515 NewClass, PrevClassTemplate);
Douglas Gregor55216ac2009-03-26 00:10:35 +0000516 NewClass->setDescribedClassTemplate(NewTemplate);
517
Anders Carlsson4ca43492009-03-26 01:24:28 +0000518 // Set the access specifier.
519 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
520
Douglas Gregord406b032009-02-06 22:42:48 +0000521 // Set the lexical context of these templates
522 NewClass->setLexicalDeclContext(CurContext);
523 NewTemplate->setLexicalDeclContext(CurContext);
524
525 if (TK == TK_Definition)
526 NewClass->startDefinition();
527
528 if (Attr)
529 ProcessDeclAttributeList(NewClass, Attr);
530
531 PushOnScopeChains(NewTemplate, S);
532
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000533 if (Invalid) {
534 NewTemplate->setInvalidDecl();
535 NewClass->setInvalidDecl();
536 }
Chris Lattner5261d0c2009-03-28 19:18:32 +0000537 return DeclPtrTy::make(NewTemplate);
Douglas Gregord406b032009-02-06 22:42:48 +0000538}
539
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000540/// \brief Checks the validity of a template parameter list, possibly
541/// considering the template parameter list from a previous
542/// declaration.
543///
544/// If an "old" template parameter list is provided, it must be
545/// equivalent (per TemplateParameterListsAreEqual) to the "new"
546/// template parameter list.
547///
548/// \param NewParams Template parameter list for a new template
549/// declaration. This template parameter list will be updated with any
550/// default arguments that are carried through from the previous
551/// template parameter list.
552///
553/// \param OldParams If provided, template parameter list from a
554/// previous declaration of the same template. Default template
555/// arguments will be merged from the old template parameter list to
556/// the new template parameter list.
557///
558/// \returns true if an error occurred, false otherwise.
559bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
560 TemplateParameterList *OldParams) {
561 bool Invalid = false;
562
563 // C++ [temp.param]p10:
564 // The set of default template-arguments available for use with a
565 // template declaration or definition is obtained by merging the
566 // default arguments from the definition (if in scope) and all
567 // declarations in scope in the same way default function
568 // arguments are (8.3.6).
569 bool SawDefaultArgument = false;
570 SourceLocation PreviousDefaultArgLoc;
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000571
Mike Stumpe0b7e032009-02-11 23:03:27 +0000572 // Dummy initialization to avoid warnings.
Douglas Gregorc5363f42009-02-11 20:46:19 +0000573 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000574 if (OldParams)
575 OldParam = OldParams->begin();
576
577 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
578 NewParamEnd = NewParams->end();
579 NewParam != NewParamEnd; ++NewParam) {
580 // Variables used to diagnose redundant default arguments
581 bool RedundantDefaultArg = false;
582 SourceLocation OldDefaultLoc;
583 SourceLocation NewDefaultLoc;
584
585 // Variables used to diagnose missing default arguments
586 bool MissingDefaultArg = false;
587
588 // Merge default arguments for template type parameters.
589 if (TemplateTypeParmDecl *NewTypeParm
590 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
591 TemplateTypeParmDecl *OldTypeParm
592 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
593
594 if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
595 NewTypeParm->hasDefaultArgument()) {
596 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
597 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
598 SawDefaultArgument = true;
599 RedundantDefaultArg = true;
600 PreviousDefaultArgLoc = NewDefaultLoc;
601 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
602 // Merge the default argument from the old declaration to the
603 // new declaration.
604 SawDefaultArgument = true;
605 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgument(),
606 OldTypeParm->getDefaultArgumentLoc(),
607 true);
608 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
609 } else if (NewTypeParm->hasDefaultArgument()) {
610 SawDefaultArgument = true;
611 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
612 } else if (SawDefaultArgument)
613 MissingDefaultArg = true;
614 }
615 // Merge default arguments for non-type template parameters
616 else if (NonTypeTemplateParmDecl *NewNonTypeParm
617 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
618 NonTypeTemplateParmDecl *OldNonTypeParm
619 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
620 if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
621 NewNonTypeParm->hasDefaultArgument()) {
622 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
623 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
624 SawDefaultArgument = true;
625 RedundantDefaultArg = true;
626 PreviousDefaultArgLoc = NewDefaultLoc;
627 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
628 // Merge the default argument from the old declaration to the
629 // new declaration.
630 SawDefaultArgument = true;
631 // FIXME: We need to create a new kind of "default argument"
632 // expression that points to a previous template template
633 // parameter.
634 NewNonTypeParm->setDefaultArgument(
635 OldNonTypeParm->getDefaultArgument());
636 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
637 } else if (NewNonTypeParm->hasDefaultArgument()) {
638 SawDefaultArgument = true;
639 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
640 } else if (SawDefaultArgument)
641 MissingDefaultArg = true;
642 }
643 // Merge default arguments for template template parameters
644 else {
645 TemplateTemplateParmDecl *NewTemplateParm
646 = cast<TemplateTemplateParmDecl>(*NewParam);
647 TemplateTemplateParmDecl *OldTemplateParm
648 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
649 if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
650 NewTemplateParm->hasDefaultArgument()) {
651 OldDefaultLoc = OldTemplateParm->getDefaultArgumentLoc();
652 NewDefaultLoc = NewTemplateParm->getDefaultArgumentLoc();
653 SawDefaultArgument = true;
654 RedundantDefaultArg = true;
655 PreviousDefaultArgLoc = NewDefaultLoc;
656 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
657 // Merge the default argument from the old declaration to the
658 // new declaration.
659 SawDefaultArgument = true;
660 // FIXME: We need to create a new kind of "default argument"
661 // expression that points to a previous template template
662 // parameter.
663 NewTemplateParm->setDefaultArgument(
664 OldTemplateParm->getDefaultArgument());
665 PreviousDefaultArgLoc = OldTemplateParm->getDefaultArgumentLoc();
666 } else if (NewTemplateParm->hasDefaultArgument()) {
667 SawDefaultArgument = true;
668 PreviousDefaultArgLoc = NewTemplateParm->getDefaultArgumentLoc();
669 } else if (SawDefaultArgument)
670 MissingDefaultArg = true;
671 }
672
673 if (RedundantDefaultArg) {
674 // C++ [temp.param]p12:
675 // A template-parameter shall not be given default arguments
676 // by two different declarations in the same scope.
677 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
678 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
679 Invalid = true;
680 } else if (MissingDefaultArg) {
681 // C++ [temp.param]p11:
682 // If a template-parameter has a default template-argument,
683 // all subsequent template-parameters shall have a default
684 // template-argument supplied.
685 Diag((*NewParam)->getLocation(),
686 diag::err_template_param_default_arg_missing);
687 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
688 Invalid = true;
689 }
690
691 // If we have an old template parameter list that we're merging
692 // in, move on to the next parameter.
693 if (OldParams)
694 ++OldParam;
695 }
696
697 return Invalid;
698}
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000699
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000700/// \brief Translates template arguments as provided by the parser
701/// into template arguments used by semantic analysis.
702static void
703translateTemplateArguments(ASTTemplateArgsPtr &TemplateArgsIn,
704 SourceLocation *TemplateArgLocs,
705 llvm::SmallVector<TemplateArgument, 16> &TemplateArgs) {
706 TemplateArgs.reserve(TemplateArgsIn.size());
707
708 void **Args = TemplateArgsIn.getArgs();
709 bool *ArgIsType = TemplateArgsIn.getArgIsType();
710 for (unsigned Arg = 0, Last = TemplateArgsIn.size(); Arg != Last; ++Arg) {
711 TemplateArgs.push_back(
712 ArgIsType[Arg]? TemplateArgument(TemplateArgLocs[Arg],
713 QualType::getFromOpaquePtr(Args[Arg]))
714 : TemplateArgument(reinterpret_cast<Expr *>(Args[Arg])));
715 }
716}
717
Douglas Gregoraabb8502009-03-31 00:43:58 +0000718/// \brief Build a canonical version of a template argument list.
719///
720/// This function builds a canonical version of the given template
721/// argument list, where each of the template arguments has been
722/// converted into its canonical form. This routine is typically used
723/// to canonicalize a template argument list when the template name
724/// itself is dependent. When the template name refers to an actual
725/// template declaration, Sema::CheckTemplateArgumentList should be
726/// used to check and canonicalize the template arguments.
727///
728/// \param TemplateArgs The incoming template arguments.
729///
730/// \param NumTemplateArgs The number of template arguments in \p
731/// TemplateArgs.
732///
733/// \param Canonical A vector to be filled with the canonical versions
734/// of the template arguments.
735///
736/// \param Context The ASTContext in which the template arguments live.
737static void CanonicalizeTemplateArguments(const TemplateArgument *TemplateArgs,
738 unsigned NumTemplateArgs,
739 llvm::SmallVectorImpl<TemplateArgument> &Canonical,
740 ASTContext &Context) {
741 Canonical.reserve(NumTemplateArgs);
742 for (unsigned Idx = 0; Idx < NumTemplateArgs; ++Idx) {
743 switch (TemplateArgs[Idx].getKind()) {
744 case TemplateArgument::Expression:
745 // FIXME: Build canonical expression (!)
746 Canonical.push_back(TemplateArgs[Idx]);
747 break;
748
749 case TemplateArgument::Declaration:
750 Canonical.push_back(TemplateArgument(SourceLocation(),
751 TemplateArgs[Idx].getAsDecl()));
752 break;
753
754 case TemplateArgument::Integral:
755 Canonical.push_back(TemplateArgument(SourceLocation(),
756 *TemplateArgs[Idx].getAsIntegral(),
757 TemplateArgs[Idx].getIntegralType()));
758
759 case TemplateArgument::Type: {
760 QualType CanonType
761 = Context.getCanonicalType(TemplateArgs[Idx].getAsType());
762 Canonical.push_back(TemplateArgument(SourceLocation(), CanonType));
763 }
764 }
765 }
766}
767
Douglas Gregordd13e842009-03-30 22:58:21 +0000768QualType Sema::CheckTemplateIdType(TemplateName Name,
769 SourceLocation TemplateLoc,
770 SourceLocation LAngleLoc,
771 const TemplateArgument *TemplateArgs,
772 unsigned NumTemplateArgs,
773 SourceLocation RAngleLoc) {
774 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregoraabb8502009-03-31 00:43:58 +0000775 if (!Template) {
776 // The template name does not resolve to a template, so we just
777 // build a dependent template-id type.
778
779 // Canonicalize the template arguments to build the canonical
780 // template-id type.
781 llvm::SmallVector<TemplateArgument, 16> CanonicalTemplateArgs;
782 CanonicalizeTemplateArguments(TemplateArgs, NumTemplateArgs,
783 CanonicalTemplateArgs, Context);
784
785 // FIXME: Get the canonical template-name
786 QualType CanonType
787 = Context.getTemplateSpecializationType(Name, &CanonicalTemplateArgs[0],
788 CanonicalTemplateArgs.size());
789
790 // Build the dependent template-id type.
791 return Context.getTemplateSpecializationType(Name, TemplateArgs,
792 NumTemplateArgs, CanonType);
793 }
Douglas Gregordd13e842009-03-30 22:58:21 +0000794
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000795 // Check that the template argument list is well-formed for this
796 // template.
797 llvm::SmallVector<TemplateArgument, 16> ConvertedTemplateArgs;
Douglas Gregordd13e842009-03-30 22:58:21 +0000798 if (CheckTemplateArgumentList(Template, TemplateLoc, LAngleLoc,
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000799 TemplateArgs, NumTemplateArgs, RAngleLoc,
800 ConvertedTemplateArgs))
801 return QualType();
802
803 assert((ConvertedTemplateArgs.size() ==
Douglas Gregordd13e842009-03-30 22:58:21 +0000804 Template->getTemplateParameters()->size()) &&
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000805 "Converted template argument list is too short!");
806
807 QualType CanonType;
808
Douglas Gregordd13e842009-03-30 22:58:21 +0000809 if (TemplateSpecializationType::anyDependentTemplateArguments(
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000810 TemplateArgs,
811 NumTemplateArgs)) {
812 // This class template specialization is a dependent
813 // type. Therefore, its canonical type is another class template
814 // specialization type that contains all of the converted
815 // arguments in canonical form. This ensures that, e.g., A<T> and
816 // A<T, T> have identical types when A is declared as:
817 //
818 // template<typename T, typename U = T> struct A;
819
Douglas Gregordd13e842009-03-30 22:58:21 +0000820 CanonType = Context.getTemplateSpecializationType(Name,
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000821 &ConvertedTemplateArgs[0],
822 ConvertedTemplateArgs.size());
Douglas Gregordd13e842009-03-30 22:58:21 +0000823 } else if (ClassTemplateDecl *ClassTemplate
824 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000825 // Find the class template specialization declaration that
826 // corresponds to these arguments.
827 llvm::FoldingSetNodeID ID;
828 ClassTemplateSpecializationDecl::Profile(ID, &ConvertedTemplateArgs[0],
829 ConvertedTemplateArgs.size());
830 void *InsertPos = 0;
831 ClassTemplateSpecializationDecl *Decl
832 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
833 if (!Decl) {
834 // This is the first time we have referenced this class template
835 // specialization. Create the canonical declaration and add it to
836 // the set of specializations.
837 Decl = ClassTemplateSpecializationDecl::Create(Context,
838 ClassTemplate->getDeclContext(),
839 TemplateLoc,
840 ClassTemplate,
841 &ConvertedTemplateArgs[0],
842 ConvertedTemplateArgs.size(),
843 0);
844 ClassTemplate->getSpecializations().InsertNode(Decl, InsertPos);
845 Decl->setLexicalDeclContext(CurContext);
846 }
847
848 CanonType = Context.getTypeDeclType(Decl);
849 }
850
851 // Build the fully-sugared type for this class template
852 // specialization, which refers back to the class template
853 // specialization we created or found.
Douglas Gregordd13e842009-03-30 22:58:21 +0000854 return Context.getTemplateSpecializationType(Name, TemplateArgs,
855 NumTemplateArgs, CanonType);
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000856}
857
Douglas Gregora08b6c72009-02-17 23:15:12 +0000858Action::TypeResult
Douglas Gregordd13e842009-03-30 22:58:21 +0000859Sema::ActOnTemplateIdType(TemplateTy TemplateD, SourceLocation TemplateLoc,
860 SourceLocation LAngleLoc,
861 ASTTemplateArgsPtr TemplateArgsIn,
862 SourceLocation *TemplateArgLocs,
863 SourceLocation RAngleLoc) {
864 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Douglas Gregor8e458f42009-02-09 18:46:07 +0000865
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000866 // Translate the parser's template argument list in our AST format.
867 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
868 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000869
Douglas Gregordd13e842009-03-30 22:58:21 +0000870 QualType Result = CheckTemplateIdType(Template, TemplateLoc, LAngleLoc,
871 &TemplateArgs[0], TemplateArgs.size(),
872 RAngleLoc);
Douglas Gregor8c795a12009-03-19 00:39:20 +0000873
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000874 TemplateArgsIn.release();
Douglas Gregor6f37b582009-02-09 19:34:22 +0000875 return Result.getAsOpaquePtr();
Douglas Gregor8e458f42009-02-09 18:46:07 +0000876}
877
Douglas Gregoraabb8502009-03-31 00:43:58 +0000878/// \brief Form a dependent template name.
879///
880/// This action forms a dependent template name given the template
881/// name and its (presumably dependent) scope specifier. For
882/// example, given "MetaFun::template apply", the scope specifier \p
883/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
884/// of the "template" keyword, and "apply" is the \p Name.
885Sema::TemplateTy
886Sema::ActOnDependentTemplateName(SourceLocation TemplateKWLoc,
887 const IdentifierInfo &Name,
888 SourceLocation NameLoc,
889 const CXXScopeSpec &SS) {
890 if (!SS.isSet() || SS.isInvalid())
891 return TemplateTy();
892
893 NestedNameSpecifier *Qualifier
894 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
895
896 // FIXME: member of the current instantiation
897
898 if (!Qualifier->isDependent()) {
899 // C++0x [temp.names]p5:
900 // If a name prefixed by the keyword template is not the name of
901 // a template, the program is ill-formed. [Note: the keyword
902 // template may not be applied to non-template members of class
903 // templates. -end note ] [ Note: as is the case with the
904 // typename prefix, the template prefix is allowed in cases
905 // where it is not strictly necessary; i.e., when the
906 // nested-name-specifier or the expression on the left of the ->
907 // or . is not dependent on a template-parameter, or the use
908 // does not appear in the scope of a template. -end note]
909 //
910 // Note: C++03 was more strict here, because it banned the use of
911 // the "template" keyword prior to a template-name that was not a
912 // dependent name. C++ DR468 relaxed this requirement (the
913 // "template" keyword is now permitted). We follow the C++0x
914 // rules, even in C++03 mode, retroactively applying the DR.
915 TemplateTy Template;
916 TemplateNameKind TNK = isTemplateName(Name, 0, Template, &SS);
917 if (TNK == TNK_Non_template) {
918 Diag(NameLoc, diag::err_template_kw_refers_to_non_template)
919 << &Name;
920 return TemplateTy();
921 }
922
923 return Template;
924 }
925
926 return TemplateTy::make(Context.getDependentTemplateName(Qualifier, &Name));
927}
928
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000929/// \brief Check that the given template argument list is well-formed
930/// for specializing the given template.
931bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
932 SourceLocation TemplateLoc,
933 SourceLocation LAngleLoc,
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000934 const TemplateArgument *TemplateArgs,
935 unsigned NumTemplateArgs,
Douglas Gregorad964b32009-02-17 01:05:43 +0000936 SourceLocation RAngleLoc,
937 llvm::SmallVectorImpl<TemplateArgument> &Converted) {
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000938 TemplateParameterList *Params = Template->getTemplateParameters();
939 unsigned NumParams = Params->size();
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000940 unsigned NumArgs = NumTemplateArgs;
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000941 bool Invalid = false;
942
943 if (NumArgs > NumParams ||
Douglas Gregorc347d8e2009-02-11 18:16:40 +0000944 NumArgs < Params->getMinRequiredArguments()) {
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000945 // FIXME: point at either the first arg beyond what we can handle,
946 // or the '>', depending on whether we have too many or too few
947 // arguments.
948 SourceRange Range;
949 if (NumArgs > NumParams)
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000950 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000951 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
952 << (NumArgs > NumParams)
953 << (isa<ClassTemplateDecl>(Template)? 0 :
954 isa<FunctionTemplateDecl>(Template)? 1 :
955 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
956 << Template << Range;
Douglas Gregorc347d8e2009-02-11 18:16:40 +0000957 Diag(Template->getLocation(), diag::note_template_decl_here)
958 << Params->getSourceRange();
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000959 Invalid = true;
960 }
961
962 // C++ [temp.arg]p1:
963 // [...] The type and form of each template-argument specified in
964 // a template-id shall match the type and form specified for the
965 // corresponding parameter declared by the template in its
966 // template-parameter-list.
967 unsigned ArgIdx = 0;
968 for (TemplateParameterList::iterator Param = Params->begin(),
969 ParamEnd = Params->end();
970 Param != ParamEnd; ++Param, ++ArgIdx) {
971 // Decode the template argument
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000972 TemplateArgument Arg;
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000973 if (ArgIdx >= NumArgs) {
Douglas Gregorad964b32009-02-17 01:05:43 +0000974 // Retrieve the default template argument from the template
975 // parameter.
976 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
977 if (!TTP->hasDefaultArgument())
978 break;
979
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000980 QualType ArgType = TTP->getDefaultArgument();
Douglas Gregor74296542009-02-27 19:31:52 +0000981
982 // If the argument type is dependent, instantiate it now based
983 // on the previously-computed template arguments.
Douglas Gregor56d25a72009-03-10 20:44:00 +0000984 if (ArgType->isDependentType()) {
985 InstantiatingTemplate Inst(*this, TemplateLoc,
986 Template, &Converted[0],
987 Converted.size(),
988 SourceRange(TemplateLoc, RAngleLoc));
Douglas Gregor74296542009-02-27 19:31:52 +0000989 ArgType = InstantiateType(ArgType, &Converted[0], Converted.size(),
990 TTP->getDefaultArgumentLoc(),
991 TTP->getDeclName());
Douglas Gregor56d25a72009-03-10 20:44:00 +0000992 }
Douglas Gregor74296542009-02-27 19:31:52 +0000993
994 if (ArgType.isNull())
Douglas Gregorf57dcd02009-02-28 00:25:32 +0000995 return true;
Douglas Gregor74296542009-02-27 19:31:52 +0000996
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000997 Arg = TemplateArgument(TTP->getLocation(), ArgType);
Douglas Gregorad964b32009-02-17 01:05:43 +0000998 } else if (NonTypeTemplateParmDecl *NTTP
999 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
1000 if (!NTTP->hasDefaultArgument())
1001 break;
1002
Douglas Gregored3a3982009-03-03 04:44:36 +00001003 // FIXME: Instantiate default argument
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001004 Arg = TemplateArgument(NTTP->getDefaultArgument());
Douglas Gregorad964b32009-02-17 01:05:43 +00001005 } else {
1006 TemplateTemplateParmDecl *TempParm
1007 = cast<TemplateTemplateParmDecl>(*Param);
1008
1009 if (!TempParm->hasDefaultArgument())
1010 break;
1011
Douglas Gregored3a3982009-03-03 04:44:36 +00001012 // FIXME: Instantiate default argument
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001013 Arg = TemplateArgument(TempParm->getDefaultArgument());
Douglas Gregorad964b32009-02-17 01:05:43 +00001014 }
1015 } else {
1016 // Retrieve the template argument produced by the user.
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001017 Arg = TemplateArgs[ArgIdx];
Douglas Gregorad964b32009-02-17 01:05:43 +00001018 }
1019
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001020
1021 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
1022 // Check template type parameters.
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001023 if (Arg.getKind() == TemplateArgument::Type) {
1024 if (CheckTemplateArgument(TTP, Arg.getAsType(), Arg.getLocation()))
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001025 Invalid = true;
Douglas Gregorad964b32009-02-17 01:05:43 +00001026
1027 // Add the converted template type argument.
1028 Converted.push_back(
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001029 TemplateArgument(Arg.getLocation(),
1030 Context.getCanonicalType(Arg.getAsType())));
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001031 continue;
1032 }
1033
1034 // C++ [temp.arg.type]p1:
1035 // A template-argument for a template-parameter which is a
1036 // type shall be a type-id.
1037
1038 // We have a template type parameter but the template argument
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001039 // is not a type.
1040 Diag(Arg.getLocation(), diag::err_template_arg_must_be_type);
Douglas Gregor341ac792009-02-10 00:53:15 +00001041 Diag((*Param)->getLocation(), diag::note_template_param_here);
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001042 Invalid = true;
1043 } else if (NonTypeTemplateParmDecl *NTTP
1044 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
1045 // Check non-type template parameters.
Douglas Gregored3a3982009-03-03 04:44:36 +00001046
1047 // Instantiate the type of the non-type template parameter with
1048 // the template arguments we've seen thus far.
1049 QualType NTTPType = NTTP->getType();
1050 if (NTTPType->isDependentType()) {
1051 // Instantiate the type of the non-type template parameter.
Douglas Gregor56d25a72009-03-10 20:44:00 +00001052 InstantiatingTemplate Inst(*this, TemplateLoc,
1053 Template, &Converted[0],
1054 Converted.size(),
1055 SourceRange(TemplateLoc, RAngleLoc));
1056
Douglas Gregored3a3982009-03-03 04:44:36 +00001057 NTTPType = InstantiateType(NTTPType,
1058 &Converted[0], Converted.size(),
1059 NTTP->getLocation(),
1060 NTTP->getDeclName());
1061 // If that worked, check the non-type template parameter type
1062 // for validity.
1063 if (!NTTPType.isNull())
1064 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
1065 NTTP->getLocation());
1066
1067 if (NTTPType.isNull()) {
1068 Invalid = true;
1069 break;
1070 }
1071 }
1072
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001073 switch (Arg.getKind()) {
1074 case TemplateArgument::Expression: {
1075 Expr *E = Arg.getAsExpr();
1076 if (CheckTemplateArgument(NTTP, NTTPType, E, &Converted))
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001077 Invalid = true;
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001078 break;
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001079 }
1080
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001081 case TemplateArgument::Declaration:
1082 case TemplateArgument::Integral:
1083 // We've already checked this template argument, so just copy
1084 // it to the list of converted arguments.
1085 Converted.push_back(Arg);
1086 break;
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001087
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001088 case TemplateArgument::Type:
1089 // We have a non-type template parameter but the template
1090 // argument is a type.
1091
1092 // C++ [temp.arg]p2:
1093 // In a template-argument, an ambiguity between a type-id and
1094 // an expression is resolved to a type-id, regardless of the
1095 // form of the corresponding template-parameter.
1096 //
1097 // We warn specifically about this case, since it can be rather
1098 // confusing for users.
1099 if (Arg.getAsType()->isFunctionType())
1100 Diag(Arg.getLocation(), diag::err_template_arg_nontype_ambig)
1101 << Arg.getAsType();
1102 else
1103 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr);
1104 Diag((*Param)->getLocation(), diag::note_template_param_here);
1105 Invalid = true;
1106 }
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001107 } else {
1108 // Check template template parameters.
1109 TemplateTemplateParmDecl *TempParm
1110 = cast<TemplateTemplateParmDecl>(*Param);
1111
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001112 switch (Arg.getKind()) {
1113 case TemplateArgument::Expression: {
1114 Expr *ArgExpr = Arg.getAsExpr();
1115 if (ArgExpr && isa<DeclRefExpr>(ArgExpr) &&
1116 isa<TemplateDecl>(cast<DeclRefExpr>(ArgExpr)->getDecl())) {
1117 if (CheckTemplateArgument(TempParm, cast<DeclRefExpr>(ArgExpr)))
1118 Invalid = true;
1119
1120 // Add the converted template argument.
1121 // FIXME: Need the "canonical" template declaration!
1122 Converted.push_back(
1123 TemplateArgument(Arg.getLocation(),
1124 cast<DeclRefExpr>(ArgExpr)->getDecl()));
1125 continue;
1126 }
1127 }
1128 // fall through
1129
1130 case TemplateArgument::Type: {
1131 // We have a template template parameter but the template
1132 // argument does not refer to a template.
1133 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
1134 Invalid = true;
1135 break;
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001136 }
1137
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001138 case TemplateArgument::Declaration:
1139 // We've already checked this template argument, so just copy
1140 // it to the list of converted arguments.
1141 Converted.push_back(Arg);
1142 break;
1143
1144 case TemplateArgument::Integral:
1145 assert(false && "Integral argument with template template parameter");
1146 break;
1147 }
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001148 }
1149 }
1150
1151 return Invalid;
1152}
1153
1154/// \brief Check a template argument against its corresponding
1155/// template type parameter.
1156///
1157/// This routine implements the semantics of C++ [temp.arg.type]. It
1158/// returns true if an error occurred, and false otherwise.
1159bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
1160 QualType Arg, SourceLocation ArgLoc) {
1161 // C++ [temp.arg.type]p2:
1162 // A local type, a type with no linkage, an unnamed type or a type
1163 // compounded from any of these types shall not be used as a
1164 // template-argument for a template type-parameter.
1165 //
1166 // FIXME: Perform the recursive and no-linkage type checks.
1167 const TagType *Tag = 0;
1168 if (const EnumType *EnumT = Arg->getAsEnumType())
1169 Tag = EnumT;
1170 else if (const RecordType *RecordT = Arg->getAsRecordType())
1171 Tag = RecordT;
1172 if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod())
1173 return Diag(ArgLoc, diag::err_template_arg_local_type)
1174 << QualType(Tag, 0);
Douglas Gregor04385782009-03-10 18:33:27 +00001175 else if (Tag && !Tag->getDecl()->getDeclName() &&
1176 !Tag->getDecl()->getTypedefForAnonDecl()) {
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001177 Diag(ArgLoc, diag::err_template_arg_unnamed_type);
1178 Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here);
1179 return true;
1180 }
1181
1182 return false;
1183}
1184
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001185/// \brief Checks whether the given template argument is the address
1186/// of an object or function according to C++ [temp.arg.nontype]p1.
Douglas Gregorad964b32009-02-17 01:05:43 +00001187bool Sema::CheckTemplateArgumentAddressOfObjectOrFunction(Expr *Arg,
1188 NamedDecl *&Entity) {
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001189 bool Invalid = false;
1190
1191 // See through any implicit casts we added to fix the type.
1192 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
1193 Arg = Cast->getSubExpr();
1194
1195 // C++ [temp.arg.nontype]p1:
1196 //
1197 // A template-argument for a non-type, non-template
1198 // template-parameter shall be one of: [...]
1199 //
1200 // -- the address of an object or function with external
1201 // linkage, including function templates and function
1202 // template-ids but excluding non-static class members,
1203 // expressed as & id-expression where the & is optional if
1204 // the name refers to a function or array, or if the
1205 // corresponding template-parameter is a reference; or
1206 DeclRefExpr *DRE = 0;
1207
1208 // Ignore (and complain about) any excess parentheses.
1209 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
1210 if (!Invalid) {
1211 Diag(Arg->getSourceRange().getBegin(),
1212 diag::err_template_arg_extra_parens)
1213 << Arg->getSourceRange();
1214 Invalid = true;
1215 }
1216
1217 Arg = Parens->getSubExpr();
1218 }
1219
1220 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
1221 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
1222 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
1223 } else
1224 DRE = dyn_cast<DeclRefExpr>(Arg);
1225
1226 if (!DRE || !isa<ValueDecl>(DRE->getDecl()))
1227 return Diag(Arg->getSourceRange().getBegin(),
1228 diag::err_template_arg_not_object_or_func_form)
1229 << Arg->getSourceRange();
1230
1231 // Cannot refer to non-static data members
1232 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl()))
1233 return Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
1234 << Field << Arg->getSourceRange();
1235
1236 // Cannot refer to non-static member functions
1237 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
1238 if (!Method->isStatic())
1239 return Diag(Arg->getSourceRange().getBegin(),
1240 diag::err_template_arg_method)
1241 << Method << Arg->getSourceRange();
1242
1243 // Functions must have external linkage.
1244 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
1245 if (Func->getStorageClass() == FunctionDecl::Static) {
1246 Diag(Arg->getSourceRange().getBegin(),
1247 diag::err_template_arg_function_not_extern)
1248 << Func << Arg->getSourceRange();
1249 Diag(Func->getLocation(), diag::note_template_arg_internal_object)
1250 << true;
1251 return true;
1252 }
1253
1254 // Okay: we've named a function with external linkage.
Douglas Gregorad964b32009-02-17 01:05:43 +00001255 Entity = Func;
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001256 return Invalid;
1257 }
1258
1259 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
1260 if (!Var->hasGlobalStorage()) {
1261 Diag(Arg->getSourceRange().getBegin(),
1262 diag::err_template_arg_object_not_extern)
1263 << Var << Arg->getSourceRange();
1264 Diag(Var->getLocation(), diag::note_template_arg_internal_object)
1265 << true;
1266 return true;
1267 }
1268
1269 // Okay: we've named an object with external linkage
Douglas Gregorad964b32009-02-17 01:05:43 +00001270 Entity = Var;
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001271 return Invalid;
1272 }
1273
1274 // We found something else, but we don't know specifically what it is.
1275 Diag(Arg->getSourceRange().getBegin(),
1276 diag::err_template_arg_not_object_or_func)
1277 << Arg->getSourceRange();
1278 Diag(DRE->getDecl()->getLocation(),
1279 diag::note_template_arg_refers_here);
1280 return true;
1281}
1282
1283/// \brief Checks whether the given template argument is a pointer to
1284/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregorad964b32009-02-17 01:05:43 +00001285bool
1286Sema::CheckTemplateArgumentPointerToMember(Expr *Arg, NamedDecl *&Member) {
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001287 bool Invalid = false;
1288
1289 // See through any implicit casts we added to fix the type.
1290 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
1291 Arg = Cast->getSubExpr();
1292
1293 // C++ [temp.arg.nontype]p1:
1294 //
1295 // A template-argument for a non-type, non-template
1296 // template-parameter shall be one of: [...]
1297 //
1298 // -- a pointer to member expressed as described in 5.3.1.
1299 QualifiedDeclRefExpr *DRE = 0;
1300
1301 // Ignore (and complain about) any excess parentheses.
1302 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
1303 if (!Invalid) {
1304 Diag(Arg->getSourceRange().getBegin(),
1305 diag::err_template_arg_extra_parens)
1306 << Arg->getSourceRange();
1307 Invalid = true;
1308 }
1309
1310 Arg = Parens->getSubExpr();
1311 }
1312
1313 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg))
1314 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
1315 DRE = dyn_cast<QualifiedDeclRefExpr>(UnOp->getSubExpr());
1316
1317 if (!DRE)
1318 return Diag(Arg->getSourceRange().getBegin(),
1319 diag::err_template_arg_not_pointer_to_member_form)
1320 << Arg->getSourceRange();
1321
1322 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
1323 assert((isa<FieldDecl>(DRE->getDecl()) ||
1324 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
1325 "Only non-static member pointers can make it here");
1326
1327 // Okay: this is the address of a non-static member, and therefore
1328 // a member pointer constant.
Douglas Gregorad964b32009-02-17 01:05:43 +00001329 Member = DRE->getDecl();
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001330 return Invalid;
1331 }
1332
1333 // We found something else, but we don't know specifically what it is.
1334 Diag(Arg->getSourceRange().getBegin(),
1335 diag::err_template_arg_not_pointer_to_member_form)
1336 << Arg->getSourceRange();
1337 Diag(DRE->getDecl()->getLocation(),
1338 diag::note_template_arg_refers_here);
1339 return true;
1340}
1341
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001342/// \brief Check a template argument against its corresponding
1343/// non-type template parameter.
1344///
Douglas Gregored3a3982009-03-03 04:44:36 +00001345/// This routine implements the semantics of C++ [temp.arg.nontype].
1346/// It returns true if an error occurred, and false otherwise. \p
1347/// InstantiatedParamType is the type of the non-type template
1348/// parameter after it has been instantiated.
Douglas Gregorad964b32009-02-17 01:05:43 +00001349///
1350/// If Converted is non-NULL and no errors occur, the value
1351/// of this argument will be added to the end of the Converted vector.
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001352bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Douglas Gregored3a3982009-03-03 04:44:36 +00001353 QualType InstantiatedParamType, Expr *&Arg,
Douglas Gregorad964b32009-02-17 01:05:43 +00001354 llvm::SmallVectorImpl<TemplateArgument> *Converted) {
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001355 SourceLocation StartLoc = Arg->getSourceRange().getBegin();
1356
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001357 // If either the parameter has a dependent type or the argument is
1358 // type-dependent, there's nothing we can check now.
Douglas Gregorad964b32009-02-17 01:05:43 +00001359 // FIXME: Add template argument to Converted!
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001360 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
1361 // FIXME: Produce a cloned, canonical expression?
1362 Converted->push_back(TemplateArgument(Arg));
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001363 return false;
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001364 }
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001365
1366 // C++ [temp.arg.nontype]p5:
1367 // The following conversions are performed on each expression used
1368 // as a non-type template-argument. If a non-type
1369 // template-argument cannot be converted to the type of the
1370 // corresponding template-parameter then the program is
1371 // ill-formed.
1372 //
1373 // -- for a non-type template-parameter of integral or
1374 // enumeration type, integral promotions (4.5) and integral
1375 // conversions (4.7) are applied.
Douglas Gregored3a3982009-03-03 04:44:36 +00001376 QualType ParamType = InstantiatedParamType;
Douglas Gregor2eedd992009-02-11 00:19:33 +00001377 QualType ArgType = Arg->getType();
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001378 if (ParamType->isIntegralType() || ParamType->isEnumeralType()) {
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001379 // C++ [temp.arg.nontype]p1:
1380 // A template-argument for a non-type, non-template
1381 // template-parameter shall be one of:
1382 //
1383 // -- an integral constant-expression of integral or enumeration
1384 // type; or
1385 // -- the name of a non-type template-parameter; or
1386 SourceLocation NonConstantLoc;
Douglas Gregorad964b32009-02-17 01:05:43 +00001387 llvm::APSInt Value;
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001388 if (!ArgType->isIntegralType() && !ArgType->isEnumeralType()) {
1389 Diag(Arg->getSourceRange().getBegin(),
1390 diag::err_template_arg_not_integral_or_enumeral)
1391 << ArgType << Arg->getSourceRange();
1392 Diag(Param->getLocation(), diag::note_template_param_here);
1393 return true;
1394 } else if (!Arg->isValueDependent() &&
Douglas Gregorad964b32009-02-17 01:05:43 +00001395 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001396 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
1397 << ArgType << Arg->getSourceRange();
1398 return true;
1399 }
1400
1401 // FIXME: We need some way to more easily get the unqualified form
1402 // of the types without going all the way to the
1403 // canonical type.
1404 if (Context.getCanonicalType(ParamType).getCVRQualifiers())
1405 ParamType = Context.getCanonicalType(ParamType).getUnqualifiedType();
1406 if (Context.getCanonicalType(ArgType).getCVRQualifiers())
1407 ArgType = Context.getCanonicalType(ArgType).getUnqualifiedType();
1408
1409 // Try to convert the argument to the parameter's type.
1410 if (ParamType == ArgType) {
1411 // Okay: no conversion necessary
1412 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
1413 !ParamType->isEnumeralType()) {
1414 // This is an integral promotion or conversion.
1415 ImpCastExprToType(Arg, ParamType);
1416 } else {
1417 // We can't perform this conversion.
1418 Diag(Arg->getSourceRange().getBegin(),
1419 diag::err_template_arg_not_convertible)
Douglas Gregored3a3982009-03-03 04:44:36 +00001420 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001421 Diag(Param->getLocation(), diag::note_template_param_here);
1422 return true;
1423 }
1424
Douglas Gregorafc86942009-03-14 00:20:21 +00001425 QualType IntegerType = Context.getCanonicalType(ParamType);
1426 if (const EnumType *Enum = IntegerType->getAsEnumType())
1427 IntegerType = Enum->getDecl()->getIntegerType();
1428
1429 if (!Arg->isValueDependent()) {
1430 // Check that an unsigned parameter does not receive a negative
1431 // value.
1432 if (IntegerType->isUnsignedIntegerType()
1433 && (Value.isSigned() && Value.isNegative())) {
1434 Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_negative)
1435 << Value.toString(10) << Param->getType()
1436 << Arg->getSourceRange();
1437 Diag(Param->getLocation(), diag::note_template_param_here);
1438 return true;
1439 }
1440
1441 // Check that we don't overflow the template parameter type.
1442 unsigned AllowedBits = Context.getTypeSize(IntegerType);
1443 if (Value.getActiveBits() > AllowedBits) {
1444 Diag(Arg->getSourceRange().getBegin(),
1445 diag::err_template_arg_too_large)
1446 << Value.toString(10) << Param->getType()
1447 << Arg->getSourceRange();
1448 Diag(Param->getLocation(), diag::note_template_param_here);
1449 return true;
1450 }
1451
1452 if (Value.getBitWidth() != AllowedBits)
1453 Value.extOrTrunc(AllowedBits);
1454 Value.setIsSigned(IntegerType->isSignedIntegerType());
1455 }
Douglas Gregorad964b32009-02-17 01:05:43 +00001456
1457 if (Converted) {
1458 // Add the value of this argument to the list of converted
1459 // arguments. We use the bitwidth and signedness of the template
1460 // parameter.
Douglas Gregor396f1142009-03-13 21:01:28 +00001461 if (Arg->isValueDependent()) {
1462 // The argument is value-dependent. Create a new
1463 // TemplateArgument with the converted expression.
1464 Converted->push_back(TemplateArgument(Arg));
1465 return false;
1466 }
1467
Douglas Gregor544cda62009-03-14 00:03:48 +00001468 Converted->push_back(TemplateArgument(StartLoc, Value,
Douglas Gregor63f5d602009-03-12 22:20:26 +00001469 Context.getCanonicalType(IntegerType)));
Douglas Gregorad964b32009-02-17 01:05:43 +00001470 }
1471
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001472 return false;
1473 }
Douglas Gregor2eedd992009-02-11 00:19:33 +00001474
Douglas Gregor3f411962009-02-11 01:18:59 +00001475 // Handle pointer-to-function, reference-to-function, and
1476 // pointer-to-member-function all in (roughly) the same way.
1477 if (// -- For a non-type template-parameter of type pointer to
1478 // function, only the function-to-pointer conversion (4.3) is
1479 // applied. If the template-argument represents a set of
1480 // overloaded functions (or a pointer to such), the matching
1481 // function is selected from the set (13.4).
1482 (ParamType->isPointerType() &&
1483 ParamType->getAsPointerType()->getPointeeType()->isFunctionType()) ||
1484 // -- For a non-type template-parameter of type reference to
1485 // function, no conversions apply. If the template-argument
1486 // represents a set of overloaded functions, the matching
1487 // function is selected from the set (13.4).
1488 (ParamType->isReferenceType() &&
1489 ParamType->getAsReferenceType()->getPointeeType()->isFunctionType()) ||
1490 // -- For a non-type template-parameter of type pointer to
1491 // member function, no conversions apply. If the
1492 // template-argument represents a set of overloaded member
1493 // functions, the matching member function is selected from
1494 // the set (13.4).
1495 (ParamType->isMemberPointerType() &&
1496 ParamType->getAsMemberPointerType()->getPointeeType()
1497 ->isFunctionType())) {
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001498 if (Context.hasSameUnqualifiedType(ArgType,
1499 ParamType.getNonReferenceType())) {
Douglas Gregor2eedd992009-02-11 00:19:33 +00001500 // We don't have to do anything: the types already match.
Douglas Gregor3f411962009-02-11 01:18:59 +00001501 } else if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregor2eedd992009-02-11 00:19:33 +00001502 ArgType = Context.getPointerType(ArgType);
1503 ImpCastExprToType(Arg, ArgType);
1504 } else if (FunctionDecl *Fn
1505 = ResolveAddressOfOverloadedFunction(Arg, ParamType, true)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00001506 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
1507 return true;
1508
Douglas Gregor2eedd992009-02-11 00:19:33 +00001509 FixOverloadedFunctionReference(Arg, Fn);
1510 ArgType = Arg->getType();
Douglas Gregor3f411962009-02-11 01:18:59 +00001511 if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregor2eedd992009-02-11 00:19:33 +00001512 ArgType = Context.getPointerType(Arg->getType());
1513 ImpCastExprToType(Arg, ArgType);
1514 }
1515 }
1516
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001517 if (!Context.hasSameUnqualifiedType(ArgType,
1518 ParamType.getNonReferenceType())) {
Douglas Gregor2eedd992009-02-11 00:19:33 +00001519 // We can't perform this conversion.
1520 Diag(Arg->getSourceRange().getBegin(),
1521 diag::err_template_arg_not_convertible)
Douglas Gregored3a3982009-03-03 04:44:36 +00001522 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor2eedd992009-02-11 00:19:33 +00001523 Diag(Param->getLocation(), diag::note_template_param_here);
1524 return true;
1525 }
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001526
Douglas Gregorad964b32009-02-17 01:05:43 +00001527 if (ParamType->isMemberPointerType()) {
1528 NamedDecl *Member = 0;
1529 if (CheckTemplateArgumentPointerToMember(Arg, Member))
1530 return true;
1531
1532 if (Converted)
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001533 Converted->push_back(TemplateArgument(StartLoc, Member));
Douglas Gregorad964b32009-02-17 01:05:43 +00001534
1535 return false;
1536 }
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001537
Douglas Gregorad964b32009-02-17 01:05:43 +00001538 NamedDecl *Entity = 0;
1539 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1540 return true;
1541
1542 if (Converted)
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001543 Converted->push_back(TemplateArgument(StartLoc, Entity));
Douglas Gregorad964b32009-02-17 01:05:43 +00001544 return false;
Douglas Gregor2eedd992009-02-11 00:19:33 +00001545 }
1546
Chris Lattner320dff22009-02-20 21:37:53 +00001547 if (ParamType->isPointerType()) {
Douglas Gregor3f411962009-02-11 01:18:59 +00001548 // -- for a non-type template-parameter of type pointer to
1549 // object, qualification conversions (4.4) and the
1550 // array-to-pointer conversion (4.2) are applied.
Douglas Gregor26ea1222009-03-24 20:32:41 +00001551 assert(ParamType->getAsPointerType()->getPointeeType()->isObjectType() &&
Douglas Gregor3f411962009-02-11 01:18:59 +00001552 "Only object pointers allowed here");
Douglas Gregord8c8c092009-02-11 00:44:29 +00001553
Douglas Gregor3f411962009-02-11 01:18:59 +00001554 if (ArgType->isArrayType()) {
1555 ArgType = Context.getArrayDecayedType(ArgType);
1556 ImpCastExprToType(Arg, ArgType);
Douglas Gregord8c8c092009-02-11 00:44:29 +00001557 }
Douglas Gregor3f411962009-02-11 01:18:59 +00001558
1559 if (IsQualificationConversion(ArgType, ParamType)) {
1560 ArgType = ParamType;
1561 ImpCastExprToType(Arg, ParamType);
1562 }
1563
Douglas Gregor0ea4e302009-02-11 18:22:40 +00001564 if (!Context.hasSameUnqualifiedType(ArgType, ParamType)) {
Douglas Gregor3f411962009-02-11 01:18:59 +00001565 // We can't perform this conversion.
1566 Diag(Arg->getSourceRange().getBegin(),
1567 diag::err_template_arg_not_convertible)
Douglas Gregored3a3982009-03-03 04:44:36 +00001568 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor3f411962009-02-11 01:18:59 +00001569 Diag(Param->getLocation(), diag::note_template_param_here);
1570 return true;
1571 }
1572
Douglas Gregorad964b32009-02-17 01:05:43 +00001573 NamedDecl *Entity = 0;
1574 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1575 return true;
1576
1577 if (Converted)
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001578 Converted->push_back(TemplateArgument(StartLoc, Entity));
Douglas Gregorad964b32009-02-17 01:05:43 +00001579
1580 return false;
Douglas Gregord8c8c092009-02-11 00:44:29 +00001581 }
Douglas Gregor3f411962009-02-11 01:18:59 +00001582
1583 if (const ReferenceType *ParamRefType = ParamType->getAsReferenceType()) {
1584 // -- For a non-type template-parameter of type reference to
1585 // object, no conversions apply. The type referred to by the
1586 // reference may be more cv-qualified than the (otherwise
1587 // identical) type of the template-argument. The
1588 // template-parameter is bound directly to the
1589 // template-argument, which must be an lvalue.
Douglas Gregor26ea1222009-03-24 20:32:41 +00001590 assert(ParamRefType->getPointeeType()->isObjectType() &&
Douglas Gregor3f411962009-02-11 01:18:59 +00001591 "Only object references allowed here");
Douglas Gregord8c8c092009-02-11 00:44:29 +00001592
Douglas Gregor0ea4e302009-02-11 18:22:40 +00001593 if (!Context.hasSameUnqualifiedType(ParamRefType->getPointeeType(), ArgType)) {
Douglas Gregor3f411962009-02-11 01:18:59 +00001594 Diag(Arg->getSourceRange().getBegin(),
1595 diag::err_template_arg_no_ref_bind)
Douglas Gregored3a3982009-03-03 04:44:36 +00001596 << InstantiatedParamType << Arg->getType()
Douglas Gregor3f411962009-02-11 01:18:59 +00001597 << Arg->getSourceRange();
1598 Diag(Param->getLocation(), diag::note_template_param_here);
1599 return true;
1600 }
1601
1602 unsigned ParamQuals
1603 = Context.getCanonicalType(ParamType).getCVRQualifiers();
1604 unsigned ArgQuals = Context.getCanonicalType(ArgType).getCVRQualifiers();
1605
1606 if ((ParamQuals | ArgQuals) != ParamQuals) {
1607 Diag(Arg->getSourceRange().getBegin(),
1608 diag::err_template_arg_ref_bind_ignores_quals)
Douglas Gregored3a3982009-03-03 04:44:36 +00001609 << InstantiatedParamType << Arg->getType()
Douglas Gregor3f411962009-02-11 01:18:59 +00001610 << Arg->getSourceRange();
1611 Diag(Param->getLocation(), diag::note_template_param_here);
1612 return true;
1613 }
1614
Douglas Gregorad964b32009-02-17 01:05:43 +00001615 NamedDecl *Entity = 0;
1616 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1617 return true;
1618
1619 if (Converted)
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001620 Converted->push_back(TemplateArgument(StartLoc, Entity));
Douglas Gregorad964b32009-02-17 01:05:43 +00001621
1622 return false;
Douglas Gregor3f411962009-02-11 01:18:59 +00001623 }
Douglas Gregor3628e1b2009-02-11 16:16:59 +00001624
1625 // -- For a non-type template-parameter of type pointer to data
1626 // member, qualification conversions (4.4) are applied.
1627 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
1628
Douglas Gregor0ea4e302009-02-11 18:22:40 +00001629 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
Douglas Gregor3628e1b2009-02-11 16:16:59 +00001630 // Types match exactly: nothing more to do here.
1631 } else if (IsQualificationConversion(ArgType, ParamType)) {
1632 ImpCastExprToType(Arg, ParamType);
1633 } else {
1634 // We can't perform this conversion.
1635 Diag(Arg->getSourceRange().getBegin(),
1636 diag::err_template_arg_not_convertible)
Douglas Gregored3a3982009-03-03 04:44:36 +00001637 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor3628e1b2009-02-11 16:16:59 +00001638 Diag(Param->getLocation(), diag::note_template_param_here);
1639 return true;
1640 }
1641
Douglas Gregorad964b32009-02-17 01:05:43 +00001642 NamedDecl *Member = 0;
1643 if (CheckTemplateArgumentPointerToMember(Arg, Member))
1644 return true;
1645
1646 if (Converted)
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001647 Converted->push_back(TemplateArgument(StartLoc, Member));
Douglas Gregorad964b32009-02-17 01:05:43 +00001648
1649 return false;
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001650}
1651
1652/// \brief Check a template argument against its corresponding
1653/// template template parameter.
1654///
1655/// This routine implements the semantics of C++ [temp.arg.template].
1656/// It returns true if an error occurred, and false otherwise.
1657bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
1658 DeclRefExpr *Arg) {
Douglas Gregore8e367f2009-02-10 00:24:35 +00001659 assert(isa<TemplateDecl>(Arg->getDecl()) && "Only template decls allowed");
1660 TemplateDecl *Template = cast<TemplateDecl>(Arg->getDecl());
1661
1662 // C++ [temp.arg.template]p1:
1663 // A template-argument for a template template-parameter shall be
1664 // the name of a class template, expressed as id-expression. Only
1665 // primary class templates are considered when matching the
1666 // template template argument with the corresponding parameter;
1667 // partial specializations are not considered even if their
1668 // parameter lists match that of the template template parameter.
1669 if (!isa<ClassTemplateDecl>(Template)) {
1670 assert(isa<FunctionTemplateDecl>(Template) &&
1671 "Only function templates are possible here");
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001672 Diag(Arg->getSourceRange().getBegin(),
1673 diag::note_template_arg_refers_here_func)
Douglas Gregore8e367f2009-02-10 00:24:35 +00001674 << Template;
1675 }
1676
1677 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
1678 Param->getTemplateParameters(),
1679 true, true,
1680 Arg->getSourceRange().getBegin());
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001681}
1682
Douglas Gregord406b032009-02-06 22:42:48 +00001683/// \brief Determine whether the given template parameter lists are
1684/// equivalent.
1685///
1686/// \param New The new template parameter list, typically written in the
1687/// source code as part of a new template declaration.
1688///
1689/// \param Old The old template parameter list, typically found via
1690/// name lookup of the template declared with this template parameter
1691/// list.
1692///
1693/// \param Complain If true, this routine will produce a diagnostic if
1694/// the template parameter lists are not equivalent.
1695///
Douglas Gregore8e367f2009-02-10 00:24:35 +00001696/// \param IsTemplateTemplateParm If true, this routine is being
1697/// called to compare the template parameter lists of a template
1698/// template parameter.
1699///
1700/// \param TemplateArgLoc If this source location is valid, then we
1701/// are actually checking the template parameter list of a template
1702/// argument (New) against the template parameter list of its
1703/// corresponding template template parameter (Old). We produce
1704/// slightly different diagnostics in this scenario.
1705///
Douglas Gregord406b032009-02-06 22:42:48 +00001706/// \returns True if the template parameter lists are equal, false
1707/// otherwise.
1708bool
1709Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
1710 TemplateParameterList *Old,
1711 bool Complain,
Douglas Gregore8e367f2009-02-10 00:24:35 +00001712 bool IsTemplateTemplateParm,
1713 SourceLocation TemplateArgLoc) {
Douglas Gregord406b032009-02-06 22:42:48 +00001714 if (Old->size() != New->size()) {
1715 if (Complain) {
Douglas Gregore8e367f2009-02-10 00:24:35 +00001716 unsigned NextDiag = diag::err_template_param_list_different_arity;
1717 if (TemplateArgLoc.isValid()) {
1718 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
1719 NextDiag = diag::note_template_param_list_different_arity;
1720 }
1721 Diag(New->getTemplateLoc(), NextDiag)
1722 << (New->size() > Old->size())
1723 << IsTemplateTemplateParm
1724 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
Douglas Gregord406b032009-02-06 22:42:48 +00001725 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
1726 << IsTemplateTemplateParm
1727 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
1728 }
1729
1730 return false;
1731 }
1732
1733 for (TemplateParameterList::iterator OldParm = Old->begin(),
1734 OldParmEnd = Old->end(), NewParm = New->begin();
1735 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
1736 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
Douglas Gregore8e367f2009-02-10 00:24:35 +00001737 unsigned NextDiag = diag::err_template_param_different_kind;
1738 if (TemplateArgLoc.isValid()) {
1739 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
1740 NextDiag = diag::note_template_param_different_kind;
1741 }
1742 Diag((*NewParm)->getLocation(), NextDiag)
Douglas Gregord406b032009-02-06 22:42:48 +00001743 << IsTemplateTemplateParm;
1744 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
1745 << IsTemplateTemplateParm;
1746 return false;
1747 }
1748
1749 if (isa<TemplateTypeParmDecl>(*OldParm)) {
1750 // Okay; all template type parameters are equivalent (since we
Douglas Gregore8e367f2009-02-10 00:24:35 +00001751 // know we're at the same index).
1752#if 0
1753 // FIXME: Enable this code in debug mode *after* we properly go
1754 // through and "instantiate" the template parameter lists of
1755 // template template parameters. It's only after this
1756 // instantiation that (1) any dependent types within the
1757 // template parameter list of the template template parameter
1758 // can be checked, and (2) the template type parameter depths
1759 // will match up.
Douglas Gregord406b032009-02-06 22:42:48 +00001760 QualType OldParmType
1761 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*OldParm));
1762 QualType NewParmType
1763 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*NewParm));
1764 assert(Context.getCanonicalType(OldParmType) ==
1765 Context.getCanonicalType(NewParmType) &&
1766 "type parameter mismatch?");
1767#endif
1768 } else if (NonTypeTemplateParmDecl *OldNTTP
1769 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
1770 // The types of non-type template parameters must agree.
1771 NonTypeTemplateParmDecl *NewNTTP
1772 = cast<NonTypeTemplateParmDecl>(*NewParm);
1773 if (Context.getCanonicalType(OldNTTP->getType()) !=
1774 Context.getCanonicalType(NewNTTP->getType())) {
1775 if (Complain) {
Douglas Gregore8e367f2009-02-10 00:24:35 +00001776 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
1777 if (TemplateArgLoc.isValid()) {
1778 Diag(TemplateArgLoc,
1779 diag::err_template_arg_template_params_mismatch);
1780 NextDiag = diag::note_template_nontype_parm_different_type;
1781 }
1782 Diag(NewNTTP->getLocation(), NextDiag)
Douglas Gregord406b032009-02-06 22:42:48 +00001783 << NewNTTP->getType()
1784 << IsTemplateTemplateParm;
1785 Diag(OldNTTP->getLocation(),
1786 diag::note_template_nontype_parm_prev_declaration)
1787 << OldNTTP->getType();
1788 }
1789 return false;
1790 }
1791 } else {
1792 // The template parameter lists of template template
1793 // parameters must agree.
1794 // FIXME: Could we perform a faster "type" comparison here?
1795 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
1796 "Only template template parameters handled here");
1797 TemplateTemplateParmDecl *OldTTP
1798 = cast<TemplateTemplateParmDecl>(*OldParm);
1799 TemplateTemplateParmDecl *NewTTP
1800 = cast<TemplateTemplateParmDecl>(*NewParm);
1801 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
1802 OldTTP->getTemplateParameters(),
1803 Complain,
Douglas Gregore8e367f2009-02-10 00:24:35 +00001804 /*IsTemplateTemplateParm=*/true,
1805 TemplateArgLoc))
Douglas Gregord406b032009-02-06 22:42:48 +00001806 return false;
1807 }
1808 }
1809
1810 return true;
1811}
1812
1813/// \brief Check whether a template can be declared within this scope.
1814///
1815/// If the template declaration is valid in this scope, returns
1816/// false. Otherwise, issues a diagnostic and returns true.
1817bool
1818Sema::CheckTemplateDeclScope(Scope *S,
1819 MultiTemplateParamsArg &TemplateParameterLists) {
1820 assert(TemplateParameterLists.size() > 0 && "Not a template");
1821
1822 // Find the nearest enclosing declaration scope.
1823 while ((S->getFlags() & Scope::DeclScope) == 0 ||
1824 (S->getFlags() & Scope::TemplateParamScope) != 0)
1825 S = S->getParent();
1826
1827 TemplateParameterList *TemplateParams =
1828 static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
1829 SourceLocation TemplateLoc = TemplateParams->getTemplateLoc();
1830 SourceRange TemplateRange
1831 = SourceRange(TemplateLoc, TemplateParams->getRAngleLoc());
1832
1833 // C++ [temp]p2:
1834 // A template-declaration can appear only as a namespace scope or
1835 // class scope declaration.
1836 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
1837 while (Ctx && isa<LinkageSpecDecl>(Ctx)) {
1838 if (cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
1839 return Diag(TemplateLoc, diag::err_template_linkage)
1840 << TemplateRange;
1841
1842 Ctx = Ctx->getParent();
1843 }
1844
1845 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
1846 return false;
1847
1848 return Diag(TemplateLoc, diag::err_template_outside_namespace_or_class_scope)
1849 << TemplateRange;
1850}
Douglas Gregora08b6c72009-02-17 23:15:12 +00001851
Douglas Gregor0d93f692009-02-25 22:02:03 +00001852/// \brief Check whether a class template specialization in the
1853/// current context is well-formed.
1854///
1855/// This routine determines whether a class template specialization
1856/// can be declared in the current context (C++ [temp.expl.spec]p2)
1857/// and emits appropriate diagnostics if there was an error. It
1858/// returns true if there was an error that we cannot recover from,
1859/// and false otherwise.
1860bool
1861Sema::CheckClassTemplateSpecializationScope(ClassTemplateDecl *ClassTemplate,
1862 ClassTemplateSpecializationDecl *PrevDecl,
1863 SourceLocation TemplateNameLoc,
1864 SourceRange ScopeSpecifierRange) {
1865 // C++ [temp.expl.spec]p2:
1866 // An explicit specialization shall be declared in the namespace
1867 // of which the template is a member, or, for member templates, in
1868 // the namespace of which the enclosing class or enclosing class
1869 // template is a member. An explicit specialization of a member
1870 // function, member class or static data member of a class
1871 // template shall be declared in the namespace of which the class
1872 // template is a member. Such a declaration may also be a
1873 // definition. If the declaration is not a definition, the
1874 // specialization may be defined later in the name- space in which
1875 // the explicit specialization was declared, or in a namespace
1876 // that encloses the one in which the explicit specialization was
1877 // declared.
1878 if (CurContext->getLookupContext()->isFunctionOrMethod()) {
1879 Diag(TemplateNameLoc, diag::err_template_spec_decl_function_scope)
1880 << ClassTemplate;
1881 return true;
1882 }
1883
1884 DeclContext *DC = CurContext->getEnclosingNamespaceContext();
1885 DeclContext *TemplateContext
1886 = ClassTemplate->getDeclContext()->getEnclosingNamespaceContext();
1887 if (!PrevDecl || PrevDecl->getSpecializationKind() == TSK_Undeclared) {
1888 // There is no prior declaration of this entity, so this
1889 // specialization must be in the same context as the template
1890 // itself.
1891 if (DC != TemplateContext) {
1892 if (isa<TranslationUnitDecl>(TemplateContext))
1893 Diag(TemplateNameLoc, diag::err_template_spec_decl_out_of_scope_global)
1894 << ClassTemplate << ScopeSpecifierRange;
1895 else if (isa<NamespaceDecl>(TemplateContext))
1896 Diag(TemplateNameLoc, diag::err_template_spec_decl_out_of_scope)
1897 << ClassTemplate << cast<NamedDecl>(TemplateContext)
1898 << ScopeSpecifierRange;
1899
1900 Diag(ClassTemplate->getLocation(), diag::note_template_decl_here);
1901 }
1902
1903 return false;
1904 }
1905
1906 // We have a previous declaration of this entity. Make sure that
1907 // this redeclaration (or definition) occurs in an enclosing namespace.
1908 if (!CurContext->Encloses(TemplateContext)) {
1909 if (isa<TranslationUnitDecl>(TemplateContext))
1910 Diag(TemplateNameLoc, diag::err_template_spec_redecl_global_scope)
1911 << ClassTemplate << ScopeSpecifierRange;
1912 else if (isa<NamespaceDecl>(TemplateContext))
1913 Diag(TemplateNameLoc, diag::err_template_spec_redecl_out_of_scope)
1914 << ClassTemplate << cast<NamedDecl>(TemplateContext)
1915 << ScopeSpecifierRange;
1916
1917 Diag(ClassTemplate->getLocation(), diag::note_template_decl_here);
1918 }
1919
1920 return false;
1921}
1922
Douglas Gregorc5d6fa72009-03-25 00:13:59 +00001923Sema::DeclResult
Douglas Gregora08b6c72009-02-17 23:15:12 +00001924Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec, TagKind TK,
1925 SourceLocation KWLoc,
1926 const CXXScopeSpec &SS,
Douglas Gregordd13e842009-03-30 22:58:21 +00001927 TemplateTy TemplateD,
Douglas Gregora08b6c72009-02-17 23:15:12 +00001928 SourceLocation TemplateNameLoc,
1929 SourceLocation LAngleLoc,
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001930 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregora08b6c72009-02-17 23:15:12 +00001931 SourceLocation *TemplateArgLocs,
1932 SourceLocation RAngleLoc,
1933 AttributeList *Attr,
1934 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregora08b6c72009-02-17 23:15:12 +00001935 // Find the class template we're specializing
Douglas Gregordd13e842009-03-30 22:58:21 +00001936 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Douglas Gregora08b6c72009-02-17 23:15:12 +00001937 ClassTemplateDecl *ClassTemplate
Douglas Gregordd13e842009-03-30 22:58:21 +00001938 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
Douglas Gregora08b6c72009-02-17 23:15:12 +00001939
Douglas Gregor0d93f692009-02-25 22:02:03 +00001940 // Check the validity of the template headers that introduce this
1941 // template.
Douglas Gregor50113ca2009-02-25 22:18:32 +00001942 // FIXME: Once we have member templates, we'll need to check
1943 // C++ [temp.expl.spec]p17-18, where we could have multiple levels of
1944 // template<> headers.
Douglas Gregor3bb30002009-02-26 21:00:50 +00001945 if (TemplateParameterLists.size() == 0)
1946 Diag(KWLoc, diag::err_template_spec_needs_header)
Douglas Gregor61be3602009-02-27 17:53:17 +00001947 << CodeModificationHint::CreateInsertion(KWLoc, "template<> ");
Douglas Gregor3bb30002009-02-26 21:00:50 +00001948 else {
Douglas Gregor0d93f692009-02-25 22:02:03 +00001949 TemplateParameterList *TemplateParams
1950 = static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
Chris Lattner5261d0c2009-03-28 19:18:32 +00001951 if (TemplateParameterLists.size() > 1) {
1952 Diag(TemplateParams->getTemplateLoc(),
1953 diag::err_template_spec_extra_headers);
1954 return true;
1955 }
Douglas Gregor0d93f692009-02-25 22:02:03 +00001956
Chris Lattner5261d0c2009-03-28 19:18:32 +00001957 if (TemplateParams->size() > 0) {
Douglas Gregor0d93f692009-02-25 22:02:03 +00001958 // FIXME: No support for class template partial specialization.
Chris Lattner5261d0c2009-03-28 19:18:32 +00001959 Diag(TemplateParams->getTemplateLoc(), diag::unsup_template_partial_spec);
1960 return true;
1961 }
Douglas Gregor0d93f692009-02-25 22:02:03 +00001962 }
1963
Douglas Gregora08b6c72009-02-17 23:15:12 +00001964 // Check that the specialization uses the same tag kind as the
1965 // original template.
1966 TagDecl::TagKind Kind;
1967 switch (TagSpec) {
1968 default: assert(0 && "Unknown tag type!");
1969 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
1970 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
1971 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
1972 }
1973 if (ClassTemplate->getTemplatedDecl()->getTagKind() != Kind) {
1974 Diag(KWLoc, diag::err_use_with_wrong_tag) << ClassTemplate;
1975 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
1976 diag::note_previous_use);
1977 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
1978 }
1979
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001980 // Translate the parser's template argument list in our AST format.
1981 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
1982 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
1983
Douglas Gregora08b6c72009-02-17 23:15:12 +00001984 // Check that the template argument list is well-formed for this
1985 // template.
1986 llvm::SmallVector<TemplateArgument, 16> ConvertedTemplateArgs;
1987 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001988 &TemplateArgs[0], TemplateArgs.size(),
1989 RAngleLoc, ConvertedTemplateArgs))
Douglas Gregorc5d6fa72009-03-25 00:13:59 +00001990 return true;
Douglas Gregora08b6c72009-02-17 23:15:12 +00001991
1992 assert((ConvertedTemplateArgs.size() ==
1993 ClassTemplate->getTemplateParameters()->size()) &&
1994 "Converted template argument list is too short!");
1995
1996 // Find the class template specialization declaration that
1997 // corresponds to these arguments.
1998 llvm::FoldingSetNodeID ID;
1999 ClassTemplateSpecializationDecl::Profile(ID, &ConvertedTemplateArgs[0],
2000 ConvertedTemplateArgs.size());
2001 void *InsertPos = 0;
2002 ClassTemplateSpecializationDecl *PrevDecl
2003 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
2004
2005 ClassTemplateSpecializationDecl *Specialization = 0;
2006
Douglas Gregor0d93f692009-02-25 22:02:03 +00002007 // Check whether we can declare a class template specialization in
2008 // the current scope.
2009 if (CheckClassTemplateSpecializationScope(ClassTemplate, PrevDecl,
2010 TemplateNameLoc,
2011 SS.getRange()))
Douglas Gregorc5d6fa72009-03-25 00:13:59 +00002012 return true;
Douglas Gregor0d93f692009-02-25 22:02:03 +00002013
Douglas Gregora08b6c72009-02-17 23:15:12 +00002014 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
2015 // Since the only prior class template specialization with these
2016 // arguments was referenced but not declared, reuse that
2017 // declaration node as our own, updating its source location to
2018 // reflect our new declaration.
Douglas Gregora08b6c72009-02-17 23:15:12 +00002019 Specialization = PrevDecl;
Douglas Gregor50113ca2009-02-25 22:18:32 +00002020 Specialization->setLocation(TemplateNameLoc);
Douglas Gregora08b6c72009-02-17 23:15:12 +00002021 PrevDecl = 0;
2022 } else {
2023 // Create a new class template specialization declaration node for
2024 // this explicit specialization.
2025 Specialization
2026 = ClassTemplateSpecializationDecl::Create(Context,
2027 ClassTemplate->getDeclContext(),
2028 TemplateNameLoc,
2029 ClassTemplate,
2030 &ConvertedTemplateArgs[0],
2031 ConvertedTemplateArgs.size(),
2032 PrevDecl);
2033
2034 if (PrevDecl) {
2035 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
2036 ClassTemplate->getSpecializations().GetOrInsertNode(Specialization);
2037 } else {
2038 ClassTemplate->getSpecializations().InsertNode(Specialization,
2039 InsertPos);
2040 }
2041 }
2042
2043 // Note that this is an explicit specialization.
2044 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
2045
2046 // Check that this isn't a redefinition of this specialization.
2047 if (TK == TK_Definition) {
2048 if (RecordDecl *Def = Specialization->getDefinition(Context)) {
2049 // FIXME: Should also handle explicit specialization after
2050 // implicit instantiation with a special diagnostic.
2051 SourceRange Range(TemplateNameLoc, RAngleLoc);
2052 Diag(TemplateNameLoc, diag::err_redefinition)
2053 << Specialization << Range;
2054 Diag(Def->getLocation(), diag::note_previous_definition);
2055 Specialization->setInvalidDecl();
Douglas Gregorc5d6fa72009-03-25 00:13:59 +00002056 return true;
Douglas Gregora08b6c72009-02-17 23:15:12 +00002057 }
2058 }
2059
Douglas Gregor9c7825b2009-02-26 22:19:44 +00002060 // Build the fully-sugared type for this class template
2061 // specialization as the user wrote in the specialization
2062 // itself. This means that we'll pretty-print the type retrieved
2063 // from the specialization's declaration the way that the user
2064 // actually wrote the specialization, rather than formatting the
2065 // name based on the "canonical" representation used to store the
2066 // template arguments in the specialization.
Douglas Gregor8c795a12009-03-19 00:39:20 +00002067 QualType WrittenTy
Douglas Gregordd13e842009-03-30 22:58:21 +00002068 = Context.getTemplateSpecializationType(Name,
2069 &TemplateArgs[0],
2070 TemplateArgs.size(),
Douglas Gregor8c795a12009-03-19 00:39:20 +00002071 Context.getTypeDeclType(Specialization));
Douglas Gregordd13e842009-03-30 22:58:21 +00002072 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00002073 TemplateArgsIn.release();
Douglas Gregora08b6c72009-02-17 23:15:12 +00002074
Douglas Gregor50113ca2009-02-25 22:18:32 +00002075 // C++ [temp.expl.spec]p9:
2076 // A template explicit specialization is in the scope of the
2077 // namespace in which the template was defined.
2078 //
2079 // We actually implement this paragraph where we set the semantic
2080 // context (in the creation of the ClassTemplateSpecializationDecl),
2081 // but we also maintain the lexical context where the actual
2082 // definition occurs.
Douglas Gregora08b6c72009-02-17 23:15:12 +00002083 Specialization->setLexicalDeclContext(CurContext);
2084
2085 // We may be starting the definition of this specialization.
2086 if (TK == TK_Definition)
2087 Specialization->startDefinition();
2088
2089 // Add the specialization into its lexical context, so that it can
2090 // be seen when iterating through the list of declarations in that
2091 // context. However, specializations are not found by name lookup.
2092 CurContext->addDecl(Specialization);
Chris Lattner5261d0c2009-03-28 19:18:32 +00002093 return DeclPtrTy::make(Specialization);
Douglas Gregora08b6c72009-02-17 23:15:12 +00002094}
Douglas Gregord3022602009-03-27 23:10:48 +00002095
2096Sema::TypeResult
2097Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
2098 const IdentifierInfo &II, SourceLocation IdLoc) {
2099 NestedNameSpecifier *NNS
2100 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
2101 if (!NNS)
2102 return true;
2103
2104 QualType T = CheckTypenameType(NNS, II, SourceRange(TypenameLoc, IdLoc));
Douglas Gregord3022602009-03-27 23:10:48 +00002105 return T.getAsOpaquePtr();
2106}
2107
Douglas Gregor77da5802009-04-01 00:28:59 +00002108Sema::TypeResult
2109Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
2110 SourceLocation TemplateLoc, TypeTy *Ty) {
2111 QualType T = QualType::getFromOpaquePtr(Ty);
2112 NestedNameSpecifier *NNS
2113 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
2114 const TemplateSpecializationType *TemplateId
2115 = T->getAsTemplateSpecializationType();
2116 assert(TemplateId && "Expected a template specialization type");
2117
2118 if (NNS->isDependent())
2119 return Context.getTypenameType(NNS, TemplateId).getAsOpaquePtr();
2120
2121 return Context.getQualifiedNameType(NNS, T).getAsOpaquePtr();
2122}
2123
Douglas Gregord3022602009-03-27 23:10:48 +00002124/// \brief Build the type that describes a C++ typename specifier,
2125/// e.g., "typename T::type".
2126QualType
2127Sema::CheckTypenameType(NestedNameSpecifier *NNS, const IdentifierInfo &II,
2128 SourceRange Range) {
2129 if (NNS->isDependent()) // FIXME: member of the current instantiation!
2130 return Context.getTypenameType(NNS, &II);
2131
2132 CXXScopeSpec SS;
2133 SS.setScopeRep(NNS);
2134 SS.setRange(Range);
2135 if (RequireCompleteDeclContext(SS))
2136 return QualType();
2137
2138 DeclContext *Ctx = computeDeclContext(SS);
2139 assert(Ctx && "No declaration context?");
2140
2141 DeclarationName Name(&II);
2142 LookupResult Result = LookupQualifiedName(Ctx, Name, LookupOrdinaryName,
2143 false);
2144 unsigned DiagID = 0;
2145 Decl *Referenced = 0;
2146 switch (Result.getKind()) {
2147 case LookupResult::NotFound:
2148 if (Ctx->isTranslationUnit())
2149 DiagID = diag::err_typename_nested_not_found_global;
2150 else
2151 DiagID = diag::err_typename_nested_not_found;
2152 break;
2153
2154 case LookupResult::Found:
2155 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getAsDecl())) {
2156 // We found a type. Build a QualifiedNameType, since the
2157 // typename-specifier was just sugar. FIXME: Tell
2158 // QualifiedNameType that it has a "typename" prefix.
2159 return Context.getQualifiedNameType(NNS, Context.getTypeDeclType(Type));
2160 }
2161
2162 DiagID = diag::err_typename_nested_not_type;
2163 Referenced = Result.getAsDecl();
2164 break;
2165
2166 case LookupResult::FoundOverloaded:
2167 DiagID = diag::err_typename_nested_not_type;
2168 Referenced = *Result.begin();
2169 break;
2170
2171 case LookupResult::AmbiguousBaseSubobjectTypes:
2172 case LookupResult::AmbiguousBaseSubobjects:
2173 case LookupResult::AmbiguousReference:
2174 DiagnoseAmbiguousLookup(Result, Name, Range.getEnd(), Range);
2175 return QualType();
2176 }
2177
2178 // If we get here, it's because name lookup did not find a
2179 // type. Emit an appropriate diagnostic and return an error.
2180 if (NamedDecl *NamedCtx = dyn_cast<NamedDecl>(Ctx))
2181 Diag(Range.getEnd(), DiagID) << Range << Name << NamedCtx;
2182 else
2183 Diag(Range.getEnd(), DiagID) << Range << Name;
2184 if (Referenced)
2185 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
2186 << Name;
2187 return QualType();
2188}