blob: abc3ac08e9fc377283f18ca89f44b00bf745aca5 [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 Gregorf9ff4b12009-03-09 23:48:35 +0000873 TemplateArgsIn.release();
Douglas Gregord7cb0372009-04-01 21:51:26 +0000874
875 if (Result.isNull())
876 return true;
877
Douglas Gregor6f37b582009-02-09 19:34:22 +0000878 return Result.getAsOpaquePtr();
Douglas Gregor8e458f42009-02-09 18:46:07 +0000879}
880
Douglas Gregoraabb8502009-03-31 00:43:58 +0000881/// \brief Form a dependent template name.
882///
883/// This action forms a dependent template name given the template
884/// name and its (presumably dependent) scope specifier. For
885/// example, given "MetaFun::template apply", the scope specifier \p
886/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
887/// of the "template" keyword, and "apply" is the \p Name.
888Sema::TemplateTy
889Sema::ActOnDependentTemplateName(SourceLocation TemplateKWLoc,
890 const IdentifierInfo &Name,
891 SourceLocation NameLoc,
892 const CXXScopeSpec &SS) {
893 if (!SS.isSet() || SS.isInvalid())
894 return TemplateTy();
895
896 NestedNameSpecifier *Qualifier
897 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
898
899 // FIXME: member of the current instantiation
900
901 if (!Qualifier->isDependent()) {
902 // C++0x [temp.names]p5:
903 // If a name prefixed by the keyword template is not the name of
904 // a template, the program is ill-formed. [Note: the keyword
905 // template may not be applied to non-template members of class
906 // templates. -end note ] [ Note: as is the case with the
907 // typename prefix, the template prefix is allowed in cases
908 // where it is not strictly necessary; i.e., when the
909 // nested-name-specifier or the expression on the left of the ->
910 // or . is not dependent on a template-parameter, or the use
911 // does not appear in the scope of a template. -end note]
912 //
913 // Note: C++03 was more strict here, because it banned the use of
914 // the "template" keyword prior to a template-name that was not a
915 // dependent name. C++ DR468 relaxed this requirement (the
916 // "template" keyword is now permitted). We follow the C++0x
917 // rules, even in C++03 mode, retroactively applying the DR.
918 TemplateTy Template;
919 TemplateNameKind TNK = isTemplateName(Name, 0, Template, &SS);
920 if (TNK == TNK_Non_template) {
921 Diag(NameLoc, diag::err_template_kw_refers_to_non_template)
922 << &Name;
923 return TemplateTy();
924 }
925
926 return Template;
927 }
928
929 return TemplateTy::make(Context.getDependentTemplateName(Qualifier, &Name));
930}
931
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000932/// \brief Check that the given template argument list is well-formed
933/// for specializing the given template.
934bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
935 SourceLocation TemplateLoc,
936 SourceLocation LAngleLoc,
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000937 const TemplateArgument *TemplateArgs,
938 unsigned NumTemplateArgs,
Douglas Gregorad964b32009-02-17 01:05:43 +0000939 SourceLocation RAngleLoc,
940 llvm::SmallVectorImpl<TemplateArgument> &Converted) {
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000941 TemplateParameterList *Params = Template->getTemplateParameters();
942 unsigned NumParams = Params->size();
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000943 unsigned NumArgs = NumTemplateArgs;
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000944 bool Invalid = false;
945
946 if (NumArgs > NumParams ||
Douglas Gregorc347d8e2009-02-11 18:16:40 +0000947 NumArgs < Params->getMinRequiredArguments()) {
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000948 // FIXME: point at either the first arg beyond what we can handle,
949 // or the '>', depending on whether we have too many or too few
950 // arguments.
951 SourceRange Range;
952 if (NumArgs > NumParams)
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000953 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000954 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
955 << (NumArgs > NumParams)
956 << (isa<ClassTemplateDecl>(Template)? 0 :
957 isa<FunctionTemplateDecl>(Template)? 1 :
958 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
959 << Template << Range;
Douglas Gregorc347d8e2009-02-11 18:16:40 +0000960 Diag(Template->getLocation(), diag::note_template_decl_here)
961 << Params->getSourceRange();
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000962 Invalid = true;
963 }
964
965 // C++ [temp.arg]p1:
966 // [...] The type and form of each template-argument specified in
967 // a template-id shall match the type and form specified for the
968 // corresponding parameter declared by the template in its
969 // template-parameter-list.
970 unsigned ArgIdx = 0;
971 for (TemplateParameterList::iterator Param = Params->begin(),
972 ParamEnd = Params->end();
973 Param != ParamEnd; ++Param, ++ArgIdx) {
974 // Decode the template argument
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000975 TemplateArgument Arg;
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000976 if (ArgIdx >= NumArgs) {
Douglas Gregorad964b32009-02-17 01:05:43 +0000977 // Retrieve the default template argument from the template
978 // parameter.
979 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
980 if (!TTP->hasDefaultArgument())
981 break;
982
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000983 QualType ArgType = TTP->getDefaultArgument();
Douglas Gregor74296542009-02-27 19:31:52 +0000984
985 // If the argument type is dependent, instantiate it now based
986 // on the previously-computed template arguments.
Douglas Gregor56d25a72009-03-10 20:44:00 +0000987 if (ArgType->isDependentType()) {
988 InstantiatingTemplate Inst(*this, TemplateLoc,
989 Template, &Converted[0],
990 Converted.size(),
991 SourceRange(TemplateLoc, RAngleLoc));
Douglas Gregor74296542009-02-27 19:31:52 +0000992 ArgType = InstantiateType(ArgType, &Converted[0], Converted.size(),
993 TTP->getDefaultArgumentLoc(),
994 TTP->getDeclName());
Douglas Gregor56d25a72009-03-10 20:44:00 +0000995 }
Douglas Gregor74296542009-02-27 19:31:52 +0000996
997 if (ArgType.isNull())
Douglas Gregorf57dcd02009-02-28 00:25:32 +0000998 return true;
Douglas Gregor74296542009-02-27 19:31:52 +0000999
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001000 Arg = TemplateArgument(TTP->getLocation(), ArgType);
Douglas Gregorad964b32009-02-17 01:05:43 +00001001 } else if (NonTypeTemplateParmDecl *NTTP
1002 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
1003 if (!NTTP->hasDefaultArgument())
1004 break;
1005
Douglas Gregored3a3982009-03-03 04:44:36 +00001006 // FIXME: Instantiate default argument
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001007 Arg = TemplateArgument(NTTP->getDefaultArgument());
Douglas Gregorad964b32009-02-17 01:05:43 +00001008 } else {
1009 TemplateTemplateParmDecl *TempParm
1010 = cast<TemplateTemplateParmDecl>(*Param);
1011
1012 if (!TempParm->hasDefaultArgument())
1013 break;
1014
Douglas Gregored3a3982009-03-03 04:44:36 +00001015 // FIXME: Instantiate default argument
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001016 Arg = TemplateArgument(TempParm->getDefaultArgument());
Douglas Gregorad964b32009-02-17 01:05:43 +00001017 }
1018 } else {
1019 // Retrieve the template argument produced by the user.
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001020 Arg = TemplateArgs[ArgIdx];
Douglas Gregorad964b32009-02-17 01:05:43 +00001021 }
1022
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001023
1024 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
1025 // Check template type parameters.
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001026 if (Arg.getKind() == TemplateArgument::Type) {
1027 if (CheckTemplateArgument(TTP, Arg.getAsType(), Arg.getLocation()))
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001028 Invalid = true;
Douglas Gregorad964b32009-02-17 01:05:43 +00001029
1030 // Add the converted template type argument.
1031 Converted.push_back(
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001032 TemplateArgument(Arg.getLocation(),
1033 Context.getCanonicalType(Arg.getAsType())));
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001034 continue;
1035 }
1036
1037 // C++ [temp.arg.type]p1:
1038 // A template-argument for a template-parameter which is a
1039 // type shall be a type-id.
1040
1041 // We have a template type parameter but the template argument
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001042 // is not a type.
1043 Diag(Arg.getLocation(), diag::err_template_arg_must_be_type);
Douglas Gregor341ac792009-02-10 00:53:15 +00001044 Diag((*Param)->getLocation(), diag::note_template_param_here);
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001045 Invalid = true;
1046 } else if (NonTypeTemplateParmDecl *NTTP
1047 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
1048 // Check non-type template parameters.
Douglas Gregored3a3982009-03-03 04:44:36 +00001049
1050 // Instantiate the type of the non-type template parameter with
1051 // the template arguments we've seen thus far.
1052 QualType NTTPType = NTTP->getType();
1053 if (NTTPType->isDependentType()) {
1054 // Instantiate the type of the non-type template parameter.
Douglas Gregor56d25a72009-03-10 20:44:00 +00001055 InstantiatingTemplate Inst(*this, TemplateLoc,
1056 Template, &Converted[0],
1057 Converted.size(),
1058 SourceRange(TemplateLoc, RAngleLoc));
1059
Douglas Gregored3a3982009-03-03 04:44:36 +00001060 NTTPType = InstantiateType(NTTPType,
1061 &Converted[0], Converted.size(),
1062 NTTP->getLocation(),
1063 NTTP->getDeclName());
1064 // If that worked, check the non-type template parameter type
1065 // for validity.
1066 if (!NTTPType.isNull())
1067 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
1068 NTTP->getLocation());
1069
1070 if (NTTPType.isNull()) {
1071 Invalid = true;
1072 break;
1073 }
1074 }
1075
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001076 switch (Arg.getKind()) {
1077 case TemplateArgument::Expression: {
1078 Expr *E = Arg.getAsExpr();
1079 if (CheckTemplateArgument(NTTP, NTTPType, E, &Converted))
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001080 Invalid = true;
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001081 break;
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001082 }
1083
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001084 case TemplateArgument::Declaration:
1085 case TemplateArgument::Integral:
1086 // We've already checked this template argument, so just copy
1087 // it to the list of converted arguments.
1088 Converted.push_back(Arg);
1089 break;
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001090
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001091 case TemplateArgument::Type:
1092 // We have a non-type template parameter but the template
1093 // argument is a type.
1094
1095 // C++ [temp.arg]p2:
1096 // In a template-argument, an ambiguity between a type-id and
1097 // an expression is resolved to a type-id, regardless of the
1098 // form of the corresponding template-parameter.
1099 //
1100 // We warn specifically about this case, since it can be rather
1101 // confusing for users.
1102 if (Arg.getAsType()->isFunctionType())
1103 Diag(Arg.getLocation(), diag::err_template_arg_nontype_ambig)
1104 << Arg.getAsType();
1105 else
1106 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr);
1107 Diag((*Param)->getLocation(), diag::note_template_param_here);
1108 Invalid = true;
1109 }
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001110 } else {
1111 // Check template template parameters.
1112 TemplateTemplateParmDecl *TempParm
1113 = cast<TemplateTemplateParmDecl>(*Param);
1114
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001115 switch (Arg.getKind()) {
1116 case TemplateArgument::Expression: {
1117 Expr *ArgExpr = Arg.getAsExpr();
1118 if (ArgExpr && isa<DeclRefExpr>(ArgExpr) &&
1119 isa<TemplateDecl>(cast<DeclRefExpr>(ArgExpr)->getDecl())) {
1120 if (CheckTemplateArgument(TempParm, cast<DeclRefExpr>(ArgExpr)))
1121 Invalid = true;
1122
1123 // Add the converted template argument.
1124 // FIXME: Need the "canonical" template declaration!
1125 Converted.push_back(
1126 TemplateArgument(Arg.getLocation(),
1127 cast<DeclRefExpr>(ArgExpr)->getDecl()));
1128 continue;
1129 }
1130 }
1131 // fall through
1132
1133 case TemplateArgument::Type: {
1134 // We have a template template parameter but the template
1135 // argument does not refer to a template.
1136 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
1137 Invalid = true;
1138 break;
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001139 }
1140
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001141 case TemplateArgument::Declaration:
1142 // We've already checked this template argument, so just copy
1143 // it to the list of converted arguments.
1144 Converted.push_back(Arg);
1145 break;
1146
1147 case TemplateArgument::Integral:
1148 assert(false && "Integral argument with template template parameter");
1149 break;
1150 }
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001151 }
1152 }
1153
1154 return Invalid;
1155}
1156
1157/// \brief Check a template argument against its corresponding
1158/// template type parameter.
1159///
1160/// This routine implements the semantics of C++ [temp.arg.type]. It
1161/// returns true if an error occurred, and false otherwise.
1162bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
1163 QualType Arg, SourceLocation ArgLoc) {
1164 // C++ [temp.arg.type]p2:
1165 // A local type, a type with no linkage, an unnamed type or a type
1166 // compounded from any of these types shall not be used as a
1167 // template-argument for a template type-parameter.
1168 //
1169 // FIXME: Perform the recursive and no-linkage type checks.
1170 const TagType *Tag = 0;
1171 if (const EnumType *EnumT = Arg->getAsEnumType())
1172 Tag = EnumT;
1173 else if (const RecordType *RecordT = Arg->getAsRecordType())
1174 Tag = RecordT;
1175 if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod())
1176 return Diag(ArgLoc, diag::err_template_arg_local_type)
1177 << QualType(Tag, 0);
Douglas Gregor04385782009-03-10 18:33:27 +00001178 else if (Tag && !Tag->getDecl()->getDeclName() &&
1179 !Tag->getDecl()->getTypedefForAnonDecl()) {
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001180 Diag(ArgLoc, diag::err_template_arg_unnamed_type);
1181 Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here);
1182 return true;
1183 }
1184
1185 return false;
1186}
1187
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001188/// \brief Checks whether the given template argument is the address
1189/// of an object or function according to C++ [temp.arg.nontype]p1.
Douglas Gregorad964b32009-02-17 01:05:43 +00001190bool Sema::CheckTemplateArgumentAddressOfObjectOrFunction(Expr *Arg,
1191 NamedDecl *&Entity) {
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001192 bool Invalid = false;
1193
1194 // See through any implicit casts we added to fix the type.
1195 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
1196 Arg = Cast->getSubExpr();
1197
1198 // C++ [temp.arg.nontype]p1:
1199 //
1200 // A template-argument for a non-type, non-template
1201 // template-parameter shall be one of: [...]
1202 //
1203 // -- the address of an object or function with external
1204 // linkage, including function templates and function
1205 // template-ids but excluding non-static class members,
1206 // expressed as & id-expression where the & is optional if
1207 // the name refers to a function or array, or if the
1208 // corresponding template-parameter is a reference; or
1209 DeclRefExpr *DRE = 0;
1210
1211 // Ignore (and complain about) any excess parentheses.
1212 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
1213 if (!Invalid) {
1214 Diag(Arg->getSourceRange().getBegin(),
1215 diag::err_template_arg_extra_parens)
1216 << Arg->getSourceRange();
1217 Invalid = true;
1218 }
1219
1220 Arg = Parens->getSubExpr();
1221 }
1222
1223 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
1224 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
1225 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
1226 } else
1227 DRE = dyn_cast<DeclRefExpr>(Arg);
1228
1229 if (!DRE || !isa<ValueDecl>(DRE->getDecl()))
1230 return Diag(Arg->getSourceRange().getBegin(),
1231 diag::err_template_arg_not_object_or_func_form)
1232 << Arg->getSourceRange();
1233
1234 // Cannot refer to non-static data members
1235 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl()))
1236 return Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
1237 << Field << Arg->getSourceRange();
1238
1239 // Cannot refer to non-static member functions
1240 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
1241 if (!Method->isStatic())
1242 return Diag(Arg->getSourceRange().getBegin(),
1243 diag::err_template_arg_method)
1244 << Method << Arg->getSourceRange();
1245
1246 // Functions must have external linkage.
1247 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
1248 if (Func->getStorageClass() == FunctionDecl::Static) {
1249 Diag(Arg->getSourceRange().getBegin(),
1250 diag::err_template_arg_function_not_extern)
1251 << Func << Arg->getSourceRange();
1252 Diag(Func->getLocation(), diag::note_template_arg_internal_object)
1253 << true;
1254 return true;
1255 }
1256
1257 // Okay: we've named a function with external linkage.
Douglas Gregorad964b32009-02-17 01:05:43 +00001258 Entity = Func;
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001259 return Invalid;
1260 }
1261
1262 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
1263 if (!Var->hasGlobalStorage()) {
1264 Diag(Arg->getSourceRange().getBegin(),
1265 diag::err_template_arg_object_not_extern)
1266 << Var << Arg->getSourceRange();
1267 Diag(Var->getLocation(), diag::note_template_arg_internal_object)
1268 << true;
1269 return true;
1270 }
1271
1272 // Okay: we've named an object with external linkage
Douglas Gregorad964b32009-02-17 01:05:43 +00001273 Entity = Var;
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001274 return Invalid;
1275 }
1276
1277 // We found something else, but we don't know specifically what it is.
1278 Diag(Arg->getSourceRange().getBegin(),
1279 diag::err_template_arg_not_object_or_func)
1280 << Arg->getSourceRange();
1281 Diag(DRE->getDecl()->getLocation(),
1282 diag::note_template_arg_refers_here);
1283 return true;
1284}
1285
1286/// \brief Checks whether the given template argument is a pointer to
1287/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregorad964b32009-02-17 01:05:43 +00001288bool
1289Sema::CheckTemplateArgumentPointerToMember(Expr *Arg, NamedDecl *&Member) {
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001290 bool Invalid = false;
1291
1292 // See through any implicit casts we added to fix the type.
1293 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
1294 Arg = Cast->getSubExpr();
1295
1296 // C++ [temp.arg.nontype]p1:
1297 //
1298 // A template-argument for a non-type, non-template
1299 // template-parameter shall be one of: [...]
1300 //
1301 // -- a pointer to member expressed as described in 5.3.1.
1302 QualifiedDeclRefExpr *DRE = 0;
1303
1304 // Ignore (and complain about) any excess parentheses.
1305 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
1306 if (!Invalid) {
1307 Diag(Arg->getSourceRange().getBegin(),
1308 diag::err_template_arg_extra_parens)
1309 << Arg->getSourceRange();
1310 Invalid = true;
1311 }
1312
1313 Arg = Parens->getSubExpr();
1314 }
1315
1316 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg))
1317 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
1318 DRE = dyn_cast<QualifiedDeclRefExpr>(UnOp->getSubExpr());
1319
1320 if (!DRE)
1321 return Diag(Arg->getSourceRange().getBegin(),
1322 diag::err_template_arg_not_pointer_to_member_form)
1323 << Arg->getSourceRange();
1324
1325 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
1326 assert((isa<FieldDecl>(DRE->getDecl()) ||
1327 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
1328 "Only non-static member pointers can make it here");
1329
1330 // Okay: this is the address of a non-static member, and therefore
1331 // a member pointer constant.
Douglas Gregorad964b32009-02-17 01:05:43 +00001332 Member = DRE->getDecl();
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001333 return Invalid;
1334 }
1335
1336 // We found something else, but we don't know specifically what it is.
1337 Diag(Arg->getSourceRange().getBegin(),
1338 diag::err_template_arg_not_pointer_to_member_form)
1339 << Arg->getSourceRange();
1340 Diag(DRE->getDecl()->getLocation(),
1341 diag::note_template_arg_refers_here);
1342 return true;
1343}
1344
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001345/// \brief Check a template argument against its corresponding
1346/// non-type template parameter.
1347///
Douglas Gregored3a3982009-03-03 04:44:36 +00001348/// This routine implements the semantics of C++ [temp.arg.nontype].
1349/// It returns true if an error occurred, and false otherwise. \p
1350/// InstantiatedParamType is the type of the non-type template
1351/// parameter after it has been instantiated.
Douglas Gregorad964b32009-02-17 01:05:43 +00001352///
1353/// If Converted is non-NULL and no errors occur, the value
1354/// of this argument will be added to the end of the Converted vector.
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001355bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Douglas Gregored3a3982009-03-03 04:44:36 +00001356 QualType InstantiatedParamType, Expr *&Arg,
Douglas Gregorad964b32009-02-17 01:05:43 +00001357 llvm::SmallVectorImpl<TemplateArgument> *Converted) {
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001358 SourceLocation StartLoc = Arg->getSourceRange().getBegin();
1359
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001360 // If either the parameter has a dependent type or the argument is
1361 // type-dependent, there's nothing we can check now.
Douglas Gregorad964b32009-02-17 01:05:43 +00001362 // FIXME: Add template argument to Converted!
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001363 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
1364 // FIXME: Produce a cloned, canonical expression?
1365 Converted->push_back(TemplateArgument(Arg));
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001366 return false;
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001367 }
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001368
1369 // C++ [temp.arg.nontype]p5:
1370 // The following conversions are performed on each expression used
1371 // as a non-type template-argument. If a non-type
1372 // template-argument cannot be converted to the type of the
1373 // corresponding template-parameter then the program is
1374 // ill-formed.
1375 //
1376 // -- for a non-type template-parameter of integral or
1377 // enumeration type, integral promotions (4.5) and integral
1378 // conversions (4.7) are applied.
Douglas Gregored3a3982009-03-03 04:44:36 +00001379 QualType ParamType = InstantiatedParamType;
Douglas Gregor2eedd992009-02-11 00:19:33 +00001380 QualType ArgType = Arg->getType();
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001381 if (ParamType->isIntegralType() || ParamType->isEnumeralType()) {
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001382 // C++ [temp.arg.nontype]p1:
1383 // A template-argument for a non-type, non-template
1384 // template-parameter shall be one of:
1385 //
1386 // -- an integral constant-expression of integral or enumeration
1387 // type; or
1388 // -- the name of a non-type template-parameter; or
1389 SourceLocation NonConstantLoc;
Douglas Gregorad964b32009-02-17 01:05:43 +00001390 llvm::APSInt Value;
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001391 if (!ArgType->isIntegralType() && !ArgType->isEnumeralType()) {
1392 Diag(Arg->getSourceRange().getBegin(),
1393 diag::err_template_arg_not_integral_or_enumeral)
1394 << ArgType << Arg->getSourceRange();
1395 Diag(Param->getLocation(), diag::note_template_param_here);
1396 return true;
1397 } else if (!Arg->isValueDependent() &&
Douglas Gregorad964b32009-02-17 01:05:43 +00001398 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001399 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
1400 << ArgType << Arg->getSourceRange();
1401 return true;
1402 }
1403
1404 // FIXME: We need some way to more easily get the unqualified form
1405 // of the types without going all the way to the
1406 // canonical type.
1407 if (Context.getCanonicalType(ParamType).getCVRQualifiers())
1408 ParamType = Context.getCanonicalType(ParamType).getUnqualifiedType();
1409 if (Context.getCanonicalType(ArgType).getCVRQualifiers())
1410 ArgType = Context.getCanonicalType(ArgType).getUnqualifiedType();
1411
1412 // Try to convert the argument to the parameter's type.
1413 if (ParamType == ArgType) {
1414 // Okay: no conversion necessary
1415 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
1416 !ParamType->isEnumeralType()) {
1417 // This is an integral promotion or conversion.
1418 ImpCastExprToType(Arg, ParamType);
1419 } else {
1420 // We can't perform this conversion.
1421 Diag(Arg->getSourceRange().getBegin(),
1422 diag::err_template_arg_not_convertible)
Douglas Gregored3a3982009-03-03 04:44:36 +00001423 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001424 Diag(Param->getLocation(), diag::note_template_param_here);
1425 return true;
1426 }
1427
Douglas Gregorafc86942009-03-14 00:20:21 +00001428 QualType IntegerType = Context.getCanonicalType(ParamType);
1429 if (const EnumType *Enum = IntegerType->getAsEnumType())
1430 IntegerType = Enum->getDecl()->getIntegerType();
1431
1432 if (!Arg->isValueDependent()) {
1433 // Check that an unsigned parameter does not receive a negative
1434 // value.
1435 if (IntegerType->isUnsignedIntegerType()
1436 && (Value.isSigned() && Value.isNegative())) {
1437 Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_negative)
1438 << Value.toString(10) << Param->getType()
1439 << Arg->getSourceRange();
1440 Diag(Param->getLocation(), diag::note_template_param_here);
1441 return true;
1442 }
1443
1444 // Check that we don't overflow the template parameter type.
1445 unsigned AllowedBits = Context.getTypeSize(IntegerType);
1446 if (Value.getActiveBits() > AllowedBits) {
1447 Diag(Arg->getSourceRange().getBegin(),
1448 diag::err_template_arg_too_large)
1449 << Value.toString(10) << Param->getType()
1450 << Arg->getSourceRange();
1451 Diag(Param->getLocation(), diag::note_template_param_here);
1452 return true;
1453 }
1454
1455 if (Value.getBitWidth() != AllowedBits)
1456 Value.extOrTrunc(AllowedBits);
1457 Value.setIsSigned(IntegerType->isSignedIntegerType());
1458 }
Douglas Gregorad964b32009-02-17 01:05:43 +00001459
1460 if (Converted) {
1461 // Add the value of this argument to the list of converted
1462 // arguments. We use the bitwidth and signedness of the template
1463 // parameter.
Douglas Gregor396f1142009-03-13 21:01:28 +00001464 if (Arg->isValueDependent()) {
1465 // The argument is value-dependent. Create a new
1466 // TemplateArgument with the converted expression.
1467 Converted->push_back(TemplateArgument(Arg));
1468 return false;
1469 }
1470
Douglas Gregor544cda62009-03-14 00:03:48 +00001471 Converted->push_back(TemplateArgument(StartLoc, Value,
Douglas Gregor63f5d602009-03-12 22:20:26 +00001472 Context.getCanonicalType(IntegerType)));
Douglas Gregorad964b32009-02-17 01:05:43 +00001473 }
1474
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001475 return false;
1476 }
Douglas Gregor2eedd992009-02-11 00:19:33 +00001477
Douglas Gregor3f411962009-02-11 01:18:59 +00001478 // Handle pointer-to-function, reference-to-function, and
1479 // pointer-to-member-function all in (roughly) the same way.
1480 if (// -- For a non-type template-parameter of type pointer to
1481 // function, only the function-to-pointer conversion (4.3) is
1482 // applied. If the template-argument represents a set of
1483 // overloaded functions (or a pointer to such), the matching
1484 // function is selected from the set (13.4).
1485 (ParamType->isPointerType() &&
1486 ParamType->getAsPointerType()->getPointeeType()->isFunctionType()) ||
1487 // -- For a non-type template-parameter of type reference to
1488 // function, no conversions apply. If the template-argument
1489 // represents a set of overloaded functions, the matching
1490 // function is selected from the set (13.4).
1491 (ParamType->isReferenceType() &&
1492 ParamType->getAsReferenceType()->getPointeeType()->isFunctionType()) ||
1493 // -- For a non-type template-parameter of type pointer to
1494 // member function, no conversions apply. If the
1495 // template-argument represents a set of overloaded member
1496 // functions, the matching member function is selected from
1497 // the set (13.4).
1498 (ParamType->isMemberPointerType() &&
1499 ParamType->getAsMemberPointerType()->getPointeeType()
1500 ->isFunctionType())) {
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001501 if (Context.hasSameUnqualifiedType(ArgType,
1502 ParamType.getNonReferenceType())) {
Douglas Gregor2eedd992009-02-11 00:19:33 +00001503 // We don't have to do anything: the types already match.
Douglas Gregor3f411962009-02-11 01:18:59 +00001504 } else if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregor2eedd992009-02-11 00:19:33 +00001505 ArgType = Context.getPointerType(ArgType);
1506 ImpCastExprToType(Arg, ArgType);
1507 } else if (FunctionDecl *Fn
1508 = ResolveAddressOfOverloadedFunction(Arg, ParamType, true)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00001509 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
1510 return true;
1511
Douglas Gregor2eedd992009-02-11 00:19:33 +00001512 FixOverloadedFunctionReference(Arg, Fn);
1513 ArgType = Arg->getType();
Douglas Gregor3f411962009-02-11 01:18:59 +00001514 if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregor2eedd992009-02-11 00:19:33 +00001515 ArgType = Context.getPointerType(Arg->getType());
1516 ImpCastExprToType(Arg, ArgType);
1517 }
1518 }
1519
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001520 if (!Context.hasSameUnqualifiedType(ArgType,
1521 ParamType.getNonReferenceType())) {
Douglas Gregor2eedd992009-02-11 00:19:33 +00001522 // We can't perform this conversion.
1523 Diag(Arg->getSourceRange().getBegin(),
1524 diag::err_template_arg_not_convertible)
Douglas Gregored3a3982009-03-03 04:44:36 +00001525 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor2eedd992009-02-11 00:19:33 +00001526 Diag(Param->getLocation(), diag::note_template_param_here);
1527 return true;
1528 }
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001529
Douglas Gregorad964b32009-02-17 01:05:43 +00001530 if (ParamType->isMemberPointerType()) {
1531 NamedDecl *Member = 0;
1532 if (CheckTemplateArgumentPointerToMember(Arg, Member))
1533 return true;
1534
1535 if (Converted)
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001536 Converted->push_back(TemplateArgument(StartLoc, Member));
Douglas Gregorad964b32009-02-17 01:05:43 +00001537
1538 return false;
1539 }
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001540
Douglas Gregorad964b32009-02-17 01:05:43 +00001541 NamedDecl *Entity = 0;
1542 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1543 return true;
1544
1545 if (Converted)
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001546 Converted->push_back(TemplateArgument(StartLoc, Entity));
Douglas Gregorad964b32009-02-17 01:05:43 +00001547 return false;
Douglas Gregor2eedd992009-02-11 00:19:33 +00001548 }
1549
Chris Lattner320dff22009-02-20 21:37:53 +00001550 if (ParamType->isPointerType()) {
Douglas Gregor3f411962009-02-11 01:18:59 +00001551 // -- for a non-type template-parameter of type pointer to
1552 // object, qualification conversions (4.4) and the
1553 // array-to-pointer conversion (4.2) are applied.
Douglas Gregor26ea1222009-03-24 20:32:41 +00001554 assert(ParamType->getAsPointerType()->getPointeeType()->isObjectType() &&
Douglas Gregor3f411962009-02-11 01:18:59 +00001555 "Only object pointers allowed here");
Douglas Gregord8c8c092009-02-11 00:44:29 +00001556
Douglas Gregor3f411962009-02-11 01:18:59 +00001557 if (ArgType->isArrayType()) {
1558 ArgType = Context.getArrayDecayedType(ArgType);
1559 ImpCastExprToType(Arg, ArgType);
Douglas Gregord8c8c092009-02-11 00:44:29 +00001560 }
Douglas Gregor3f411962009-02-11 01:18:59 +00001561
1562 if (IsQualificationConversion(ArgType, ParamType)) {
1563 ArgType = ParamType;
1564 ImpCastExprToType(Arg, ParamType);
1565 }
1566
Douglas Gregor0ea4e302009-02-11 18:22:40 +00001567 if (!Context.hasSameUnqualifiedType(ArgType, ParamType)) {
Douglas Gregor3f411962009-02-11 01:18:59 +00001568 // We can't perform this conversion.
1569 Diag(Arg->getSourceRange().getBegin(),
1570 diag::err_template_arg_not_convertible)
Douglas Gregored3a3982009-03-03 04:44:36 +00001571 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor3f411962009-02-11 01:18:59 +00001572 Diag(Param->getLocation(), diag::note_template_param_here);
1573 return true;
1574 }
1575
Douglas Gregorad964b32009-02-17 01:05:43 +00001576 NamedDecl *Entity = 0;
1577 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1578 return true;
1579
1580 if (Converted)
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001581 Converted->push_back(TemplateArgument(StartLoc, Entity));
Douglas Gregorad964b32009-02-17 01:05:43 +00001582
1583 return false;
Douglas Gregord8c8c092009-02-11 00:44:29 +00001584 }
Douglas Gregor3f411962009-02-11 01:18:59 +00001585
1586 if (const ReferenceType *ParamRefType = ParamType->getAsReferenceType()) {
1587 // -- For a non-type template-parameter of type reference to
1588 // object, no conversions apply. The type referred to by the
1589 // reference may be more cv-qualified than the (otherwise
1590 // identical) type of the template-argument. The
1591 // template-parameter is bound directly to the
1592 // template-argument, which must be an lvalue.
Douglas Gregor26ea1222009-03-24 20:32:41 +00001593 assert(ParamRefType->getPointeeType()->isObjectType() &&
Douglas Gregor3f411962009-02-11 01:18:59 +00001594 "Only object references allowed here");
Douglas Gregord8c8c092009-02-11 00:44:29 +00001595
Douglas Gregor0ea4e302009-02-11 18:22:40 +00001596 if (!Context.hasSameUnqualifiedType(ParamRefType->getPointeeType(), ArgType)) {
Douglas Gregor3f411962009-02-11 01:18:59 +00001597 Diag(Arg->getSourceRange().getBegin(),
1598 diag::err_template_arg_no_ref_bind)
Douglas Gregored3a3982009-03-03 04:44:36 +00001599 << InstantiatedParamType << Arg->getType()
Douglas Gregor3f411962009-02-11 01:18:59 +00001600 << Arg->getSourceRange();
1601 Diag(Param->getLocation(), diag::note_template_param_here);
1602 return true;
1603 }
1604
1605 unsigned ParamQuals
1606 = Context.getCanonicalType(ParamType).getCVRQualifiers();
1607 unsigned ArgQuals = Context.getCanonicalType(ArgType).getCVRQualifiers();
1608
1609 if ((ParamQuals | ArgQuals) != ParamQuals) {
1610 Diag(Arg->getSourceRange().getBegin(),
1611 diag::err_template_arg_ref_bind_ignores_quals)
Douglas Gregored3a3982009-03-03 04:44:36 +00001612 << InstantiatedParamType << Arg->getType()
Douglas Gregor3f411962009-02-11 01:18:59 +00001613 << Arg->getSourceRange();
1614 Diag(Param->getLocation(), diag::note_template_param_here);
1615 return true;
1616 }
1617
Douglas Gregorad964b32009-02-17 01:05:43 +00001618 NamedDecl *Entity = 0;
1619 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1620 return true;
1621
1622 if (Converted)
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001623 Converted->push_back(TemplateArgument(StartLoc, Entity));
Douglas Gregorad964b32009-02-17 01:05:43 +00001624
1625 return false;
Douglas Gregor3f411962009-02-11 01:18:59 +00001626 }
Douglas Gregor3628e1b2009-02-11 16:16:59 +00001627
1628 // -- For a non-type template-parameter of type pointer to data
1629 // member, qualification conversions (4.4) are applied.
1630 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
1631
Douglas Gregor0ea4e302009-02-11 18:22:40 +00001632 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
Douglas Gregor3628e1b2009-02-11 16:16:59 +00001633 // Types match exactly: nothing more to do here.
1634 } else if (IsQualificationConversion(ArgType, ParamType)) {
1635 ImpCastExprToType(Arg, ParamType);
1636 } else {
1637 // We can't perform this conversion.
1638 Diag(Arg->getSourceRange().getBegin(),
1639 diag::err_template_arg_not_convertible)
Douglas Gregored3a3982009-03-03 04:44:36 +00001640 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor3628e1b2009-02-11 16:16:59 +00001641 Diag(Param->getLocation(), diag::note_template_param_here);
1642 return true;
1643 }
1644
Douglas Gregorad964b32009-02-17 01:05:43 +00001645 NamedDecl *Member = 0;
1646 if (CheckTemplateArgumentPointerToMember(Arg, Member))
1647 return true;
1648
1649 if (Converted)
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001650 Converted->push_back(TemplateArgument(StartLoc, Member));
Douglas Gregorad964b32009-02-17 01:05:43 +00001651
1652 return false;
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001653}
1654
1655/// \brief Check a template argument against its corresponding
1656/// template template parameter.
1657///
1658/// This routine implements the semantics of C++ [temp.arg.template].
1659/// It returns true if an error occurred, and false otherwise.
1660bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
1661 DeclRefExpr *Arg) {
Douglas Gregore8e367f2009-02-10 00:24:35 +00001662 assert(isa<TemplateDecl>(Arg->getDecl()) && "Only template decls allowed");
1663 TemplateDecl *Template = cast<TemplateDecl>(Arg->getDecl());
1664
1665 // C++ [temp.arg.template]p1:
1666 // A template-argument for a template template-parameter shall be
1667 // the name of a class template, expressed as id-expression. Only
1668 // primary class templates are considered when matching the
1669 // template template argument with the corresponding parameter;
1670 // partial specializations are not considered even if their
1671 // parameter lists match that of the template template parameter.
1672 if (!isa<ClassTemplateDecl>(Template)) {
1673 assert(isa<FunctionTemplateDecl>(Template) &&
1674 "Only function templates are possible here");
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001675 Diag(Arg->getSourceRange().getBegin(),
1676 diag::note_template_arg_refers_here_func)
Douglas Gregore8e367f2009-02-10 00:24:35 +00001677 << Template;
1678 }
1679
1680 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
1681 Param->getTemplateParameters(),
1682 true, true,
1683 Arg->getSourceRange().getBegin());
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001684}
1685
Douglas Gregord406b032009-02-06 22:42:48 +00001686/// \brief Determine whether the given template parameter lists are
1687/// equivalent.
1688///
1689/// \param New The new template parameter list, typically written in the
1690/// source code as part of a new template declaration.
1691///
1692/// \param Old The old template parameter list, typically found via
1693/// name lookup of the template declared with this template parameter
1694/// list.
1695///
1696/// \param Complain If true, this routine will produce a diagnostic if
1697/// the template parameter lists are not equivalent.
1698///
Douglas Gregore8e367f2009-02-10 00:24:35 +00001699/// \param IsTemplateTemplateParm If true, this routine is being
1700/// called to compare the template parameter lists of a template
1701/// template parameter.
1702///
1703/// \param TemplateArgLoc If this source location is valid, then we
1704/// are actually checking the template parameter list of a template
1705/// argument (New) against the template parameter list of its
1706/// corresponding template template parameter (Old). We produce
1707/// slightly different diagnostics in this scenario.
1708///
Douglas Gregord406b032009-02-06 22:42:48 +00001709/// \returns True if the template parameter lists are equal, false
1710/// otherwise.
1711bool
1712Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
1713 TemplateParameterList *Old,
1714 bool Complain,
Douglas Gregore8e367f2009-02-10 00:24:35 +00001715 bool IsTemplateTemplateParm,
1716 SourceLocation TemplateArgLoc) {
Douglas Gregord406b032009-02-06 22:42:48 +00001717 if (Old->size() != New->size()) {
1718 if (Complain) {
Douglas Gregore8e367f2009-02-10 00:24:35 +00001719 unsigned NextDiag = diag::err_template_param_list_different_arity;
1720 if (TemplateArgLoc.isValid()) {
1721 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
1722 NextDiag = diag::note_template_param_list_different_arity;
1723 }
1724 Diag(New->getTemplateLoc(), NextDiag)
1725 << (New->size() > Old->size())
1726 << IsTemplateTemplateParm
1727 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
Douglas Gregord406b032009-02-06 22:42:48 +00001728 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
1729 << IsTemplateTemplateParm
1730 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
1731 }
1732
1733 return false;
1734 }
1735
1736 for (TemplateParameterList::iterator OldParm = Old->begin(),
1737 OldParmEnd = Old->end(), NewParm = New->begin();
1738 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
1739 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
Douglas Gregore8e367f2009-02-10 00:24:35 +00001740 unsigned NextDiag = diag::err_template_param_different_kind;
1741 if (TemplateArgLoc.isValid()) {
1742 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
1743 NextDiag = diag::note_template_param_different_kind;
1744 }
1745 Diag((*NewParm)->getLocation(), NextDiag)
Douglas Gregord406b032009-02-06 22:42:48 +00001746 << IsTemplateTemplateParm;
1747 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
1748 << IsTemplateTemplateParm;
1749 return false;
1750 }
1751
1752 if (isa<TemplateTypeParmDecl>(*OldParm)) {
1753 // Okay; all template type parameters are equivalent (since we
Douglas Gregore8e367f2009-02-10 00:24:35 +00001754 // know we're at the same index).
1755#if 0
1756 // FIXME: Enable this code in debug mode *after* we properly go
1757 // through and "instantiate" the template parameter lists of
1758 // template template parameters. It's only after this
1759 // instantiation that (1) any dependent types within the
1760 // template parameter list of the template template parameter
1761 // can be checked, and (2) the template type parameter depths
1762 // will match up.
Douglas Gregord406b032009-02-06 22:42:48 +00001763 QualType OldParmType
1764 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*OldParm));
1765 QualType NewParmType
1766 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*NewParm));
1767 assert(Context.getCanonicalType(OldParmType) ==
1768 Context.getCanonicalType(NewParmType) &&
1769 "type parameter mismatch?");
1770#endif
1771 } else if (NonTypeTemplateParmDecl *OldNTTP
1772 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
1773 // The types of non-type template parameters must agree.
1774 NonTypeTemplateParmDecl *NewNTTP
1775 = cast<NonTypeTemplateParmDecl>(*NewParm);
1776 if (Context.getCanonicalType(OldNTTP->getType()) !=
1777 Context.getCanonicalType(NewNTTP->getType())) {
1778 if (Complain) {
Douglas Gregore8e367f2009-02-10 00:24:35 +00001779 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
1780 if (TemplateArgLoc.isValid()) {
1781 Diag(TemplateArgLoc,
1782 diag::err_template_arg_template_params_mismatch);
1783 NextDiag = diag::note_template_nontype_parm_different_type;
1784 }
1785 Diag(NewNTTP->getLocation(), NextDiag)
Douglas Gregord406b032009-02-06 22:42:48 +00001786 << NewNTTP->getType()
1787 << IsTemplateTemplateParm;
1788 Diag(OldNTTP->getLocation(),
1789 diag::note_template_nontype_parm_prev_declaration)
1790 << OldNTTP->getType();
1791 }
1792 return false;
1793 }
1794 } else {
1795 // The template parameter lists of template template
1796 // parameters must agree.
1797 // FIXME: Could we perform a faster "type" comparison here?
1798 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
1799 "Only template template parameters handled here");
1800 TemplateTemplateParmDecl *OldTTP
1801 = cast<TemplateTemplateParmDecl>(*OldParm);
1802 TemplateTemplateParmDecl *NewTTP
1803 = cast<TemplateTemplateParmDecl>(*NewParm);
1804 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
1805 OldTTP->getTemplateParameters(),
1806 Complain,
Douglas Gregore8e367f2009-02-10 00:24:35 +00001807 /*IsTemplateTemplateParm=*/true,
1808 TemplateArgLoc))
Douglas Gregord406b032009-02-06 22:42:48 +00001809 return false;
1810 }
1811 }
1812
1813 return true;
1814}
1815
1816/// \brief Check whether a template can be declared within this scope.
1817///
1818/// If the template declaration is valid in this scope, returns
1819/// false. Otherwise, issues a diagnostic and returns true.
1820bool
1821Sema::CheckTemplateDeclScope(Scope *S,
1822 MultiTemplateParamsArg &TemplateParameterLists) {
1823 assert(TemplateParameterLists.size() > 0 && "Not a template");
1824
1825 // Find the nearest enclosing declaration scope.
1826 while ((S->getFlags() & Scope::DeclScope) == 0 ||
1827 (S->getFlags() & Scope::TemplateParamScope) != 0)
1828 S = S->getParent();
1829
1830 TemplateParameterList *TemplateParams =
1831 static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
1832 SourceLocation TemplateLoc = TemplateParams->getTemplateLoc();
1833 SourceRange TemplateRange
1834 = SourceRange(TemplateLoc, TemplateParams->getRAngleLoc());
1835
1836 // C++ [temp]p2:
1837 // A template-declaration can appear only as a namespace scope or
1838 // class scope declaration.
1839 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
1840 while (Ctx && isa<LinkageSpecDecl>(Ctx)) {
1841 if (cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
1842 return Diag(TemplateLoc, diag::err_template_linkage)
1843 << TemplateRange;
1844
1845 Ctx = Ctx->getParent();
1846 }
1847
1848 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
1849 return false;
1850
1851 return Diag(TemplateLoc, diag::err_template_outside_namespace_or_class_scope)
1852 << TemplateRange;
1853}
Douglas Gregora08b6c72009-02-17 23:15:12 +00001854
Douglas Gregor0d93f692009-02-25 22:02:03 +00001855/// \brief Check whether a class template specialization in the
1856/// current context is well-formed.
1857///
1858/// This routine determines whether a class template specialization
1859/// can be declared in the current context (C++ [temp.expl.spec]p2)
1860/// and emits appropriate diagnostics if there was an error. It
1861/// returns true if there was an error that we cannot recover from,
1862/// and false otherwise.
1863bool
1864Sema::CheckClassTemplateSpecializationScope(ClassTemplateDecl *ClassTemplate,
1865 ClassTemplateSpecializationDecl *PrevDecl,
1866 SourceLocation TemplateNameLoc,
1867 SourceRange ScopeSpecifierRange) {
1868 // C++ [temp.expl.spec]p2:
1869 // An explicit specialization shall be declared in the namespace
1870 // of which the template is a member, or, for member templates, in
1871 // the namespace of which the enclosing class or enclosing class
1872 // template is a member. An explicit specialization of a member
1873 // function, member class or static data member of a class
1874 // template shall be declared in the namespace of which the class
1875 // template is a member. Such a declaration may also be a
1876 // definition. If the declaration is not a definition, the
1877 // specialization may be defined later in the name- space in which
1878 // the explicit specialization was declared, or in a namespace
1879 // that encloses the one in which the explicit specialization was
1880 // declared.
1881 if (CurContext->getLookupContext()->isFunctionOrMethod()) {
1882 Diag(TemplateNameLoc, diag::err_template_spec_decl_function_scope)
1883 << ClassTemplate;
1884 return true;
1885 }
1886
1887 DeclContext *DC = CurContext->getEnclosingNamespaceContext();
1888 DeclContext *TemplateContext
1889 = ClassTemplate->getDeclContext()->getEnclosingNamespaceContext();
1890 if (!PrevDecl || PrevDecl->getSpecializationKind() == TSK_Undeclared) {
1891 // There is no prior declaration of this entity, so this
1892 // specialization must be in the same context as the template
1893 // itself.
1894 if (DC != TemplateContext) {
1895 if (isa<TranslationUnitDecl>(TemplateContext))
1896 Diag(TemplateNameLoc, diag::err_template_spec_decl_out_of_scope_global)
1897 << ClassTemplate << ScopeSpecifierRange;
1898 else if (isa<NamespaceDecl>(TemplateContext))
1899 Diag(TemplateNameLoc, diag::err_template_spec_decl_out_of_scope)
1900 << ClassTemplate << cast<NamedDecl>(TemplateContext)
1901 << ScopeSpecifierRange;
1902
1903 Diag(ClassTemplate->getLocation(), diag::note_template_decl_here);
1904 }
1905
1906 return false;
1907 }
1908
1909 // We have a previous declaration of this entity. Make sure that
1910 // this redeclaration (or definition) occurs in an enclosing namespace.
1911 if (!CurContext->Encloses(TemplateContext)) {
1912 if (isa<TranslationUnitDecl>(TemplateContext))
1913 Diag(TemplateNameLoc, diag::err_template_spec_redecl_global_scope)
1914 << ClassTemplate << ScopeSpecifierRange;
1915 else if (isa<NamespaceDecl>(TemplateContext))
1916 Diag(TemplateNameLoc, diag::err_template_spec_redecl_out_of_scope)
1917 << ClassTemplate << cast<NamedDecl>(TemplateContext)
1918 << ScopeSpecifierRange;
1919
1920 Diag(ClassTemplate->getLocation(), diag::note_template_decl_here);
1921 }
1922
1923 return false;
1924}
1925
Douglas Gregorc5d6fa72009-03-25 00:13:59 +00001926Sema::DeclResult
Douglas Gregora08b6c72009-02-17 23:15:12 +00001927Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec, TagKind TK,
1928 SourceLocation KWLoc,
1929 const CXXScopeSpec &SS,
Douglas Gregordd13e842009-03-30 22:58:21 +00001930 TemplateTy TemplateD,
Douglas Gregora08b6c72009-02-17 23:15:12 +00001931 SourceLocation TemplateNameLoc,
1932 SourceLocation LAngleLoc,
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001933 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregora08b6c72009-02-17 23:15:12 +00001934 SourceLocation *TemplateArgLocs,
1935 SourceLocation RAngleLoc,
1936 AttributeList *Attr,
1937 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregora08b6c72009-02-17 23:15:12 +00001938 // Find the class template we're specializing
Douglas Gregordd13e842009-03-30 22:58:21 +00001939 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Douglas Gregora08b6c72009-02-17 23:15:12 +00001940 ClassTemplateDecl *ClassTemplate
Douglas Gregordd13e842009-03-30 22:58:21 +00001941 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
Douglas Gregora08b6c72009-02-17 23:15:12 +00001942
Douglas Gregor0d93f692009-02-25 22:02:03 +00001943 // Check the validity of the template headers that introduce this
1944 // template.
Douglas Gregor50113ca2009-02-25 22:18:32 +00001945 // FIXME: Once we have member templates, we'll need to check
1946 // C++ [temp.expl.spec]p17-18, where we could have multiple levels of
1947 // template<> headers.
Douglas Gregor3bb30002009-02-26 21:00:50 +00001948 if (TemplateParameterLists.size() == 0)
1949 Diag(KWLoc, diag::err_template_spec_needs_header)
Douglas Gregor61be3602009-02-27 17:53:17 +00001950 << CodeModificationHint::CreateInsertion(KWLoc, "template<> ");
Douglas Gregor3bb30002009-02-26 21:00:50 +00001951 else {
Douglas Gregor0d93f692009-02-25 22:02:03 +00001952 TemplateParameterList *TemplateParams
1953 = static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
Chris Lattner5261d0c2009-03-28 19:18:32 +00001954 if (TemplateParameterLists.size() > 1) {
1955 Diag(TemplateParams->getTemplateLoc(),
1956 diag::err_template_spec_extra_headers);
1957 return true;
1958 }
Douglas Gregor0d93f692009-02-25 22:02:03 +00001959
Chris Lattner5261d0c2009-03-28 19:18:32 +00001960 if (TemplateParams->size() > 0) {
Douglas Gregor0d93f692009-02-25 22:02:03 +00001961 // FIXME: No support for class template partial specialization.
Chris Lattner5261d0c2009-03-28 19:18:32 +00001962 Diag(TemplateParams->getTemplateLoc(), diag::unsup_template_partial_spec);
1963 return true;
1964 }
Douglas Gregor0d93f692009-02-25 22:02:03 +00001965 }
1966
Douglas Gregora08b6c72009-02-17 23:15:12 +00001967 // Check that the specialization uses the same tag kind as the
1968 // original template.
1969 TagDecl::TagKind Kind;
1970 switch (TagSpec) {
1971 default: assert(0 && "Unknown tag type!");
1972 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
1973 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
1974 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
1975 }
1976 if (ClassTemplate->getTemplatedDecl()->getTagKind() != Kind) {
1977 Diag(KWLoc, diag::err_use_with_wrong_tag) << ClassTemplate;
1978 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
1979 diag::note_previous_use);
1980 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
1981 }
1982
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001983 // Translate the parser's template argument list in our AST format.
1984 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
1985 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
1986
Douglas Gregora08b6c72009-02-17 23:15:12 +00001987 // Check that the template argument list is well-formed for this
1988 // template.
1989 llvm::SmallVector<TemplateArgument, 16> ConvertedTemplateArgs;
1990 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001991 &TemplateArgs[0], TemplateArgs.size(),
1992 RAngleLoc, ConvertedTemplateArgs))
Douglas Gregorc5d6fa72009-03-25 00:13:59 +00001993 return true;
Douglas Gregora08b6c72009-02-17 23:15:12 +00001994
1995 assert((ConvertedTemplateArgs.size() ==
1996 ClassTemplate->getTemplateParameters()->size()) &&
1997 "Converted template argument list is too short!");
1998
1999 // Find the class template specialization declaration that
2000 // corresponds to these arguments.
2001 llvm::FoldingSetNodeID ID;
2002 ClassTemplateSpecializationDecl::Profile(ID, &ConvertedTemplateArgs[0],
2003 ConvertedTemplateArgs.size());
2004 void *InsertPos = 0;
2005 ClassTemplateSpecializationDecl *PrevDecl
2006 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
2007
2008 ClassTemplateSpecializationDecl *Specialization = 0;
2009
Douglas Gregor0d93f692009-02-25 22:02:03 +00002010 // Check whether we can declare a class template specialization in
2011 // the current scope.
2012 if (CheckClassTemplateSpecializationScope(ClassTemplate, PrevDecl,
2013 TemplateNameLoc,
2014 SS.getRange()))
Douglas Gregorc5d6fa72009-03-25 00:13:59 +00002015 return true;
Douglas Gregor0d93f692009-02-25 22:02:03 +00002016
Douglas Gregora08b6c72009-02-17 23:15:12 +00002017 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
2018 // Since the only prior class template specialization with these
2019 // arguments was referenced but not declared, reuse that
2020 // declaration node as our own, updating its source location to
2021 // reflect our new declaration.
Douglas Gregora08b6c72009-02-17 23:15:12 +00002022 Specialization = PrevDecl;
Douglas Gregor50113ca2009-02-25 22:18:32 +00002023 Specialization->setLocation(TemplateNameLoc);
Douglas Gregora08b6c72009-02-17 23:15:12 +00002024 PrevDecl = 0;
2025 } else {
2026 // Create a new class template specialization declaration node for
2027 // this explicit specialization.
2028 Specialization
2029 = ClassTemplateSpecializationDecl::Create(Context,
2030 ClassTemplate->getDeclContext(),
2031 TemplateNameLoc,
2032 ClassTemplate,
2033 &ConvertedTemplateArgs[0],
2034 ConvertedTemplateArgs.size(),
2035 PrevDecl);
2036
2037 if (PrevDecl) {
2038 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
2039 ClassTemplate->getSpecializations().GetOrInsertNode(Specialization);
2040 } else {
2041 ClassTemplate->getSpecializations().InsertNode(Specialization,
2042 InsertPos);
2043 }
2044 }
2045
2046 // Note that this is an explicit specialization.
2047 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
2048
2049 // Check that this isn't a redefinition of this specialization.
2050 if (TK == TK_Definition) {
2051 if (RecordDecl *Def = Specialization->getDefinition(Context)) {
2052 // FIXME: Should also handle explicit specialization after
2053 // implicit instantiation with a special diagnostic.
2054 SourceRange Range(TemplateNameLoc, RAngleLoc);
2055 Diag(TemplateNameLoc, diag::err_redefinition)
2056 << Specialization << Range;
2057 Diag(Def->getLocation(), diag::note_previous_definition);
2058 Specialization->setInvalidDecl();
Douglas Gregorc5d6fa72009-03-25 00:13:59 +00002059 return true;
Douglas Gregora08b6c72009-02-17 23:15:12 +00002060 }
2061 }
2062
Douglas Gregor9c7825b2009-02-26 22:19:44 +00002063 // Build the fully-sugared type for this class template
2064 // specialization as the user wrote in the specialization
2065 // itself. This means that we'll pretty-print the type retrieved
2066 // from the specialization's declaration the way that the user
2067 // actually wrote the specialization, rather than formatting the
2068 // name based on the "canonical" representation used to store the
2069 // template arguments in the specialization.
Douglas Gregor8c795a12009-03-19 00:39:20 +00002070 QualType WrittenTy
Douglas Gregordd13e842009-03-30 22:58:21 +00002071 = Context.getTemplateSpecializationType(Name,
2072 &TemplateArgs[0],
2073 TemplateArgs.size(),
Douglas Gregor8c795a12009-03-19 00:39:20 +00002074 Context.getTypeDeclType(Specialization));
Douglas Gregordd13e842009-03-30 22:58:21 +00002075 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00002076 TemplateArgsIn.release();
Douglas Gregora08b6c72009-02-17 23:15:12 +00002077
Douglas Gregor50113ca2009-02-25 22:18:32 +00002078 // C++ [temp.expl.spec]p9:
2079 // A template explicit specialization is in the scope of the
2080 // namespace in which the template was defined.
2081 //
2082 // We actually implement this paragraph where we set the semantic
2083 // context (in the creation of the ClassTemplateSpecializationDecl),
2084 // but we also maintain the lexical context where the actual
2085 // definition occurs.
Douglas Gregora08b6c72009-02-17 23:15:12 +00002086 Specialization->setLexicalDeclContext(CurContext);
2087
2088 // We may be starting the definition of this specialization.
2089 if (TK == TK_Definition)
2090 Specialization->startDefinition();
2091
2092 // Add the specialization into its lexical context, so that it can
2093 // be seen when iterating through the list of declarations in that
2094 // context. However, specializations are not found by name lookup.
2095 CurContext->addDecl(Specialization);
Chris Lattner5261d0c2009-03-28 19:18:32 +00002096 return DeclPtrTy::make(Specialization);
Douglas Gregora08b6c72009-02-17 23:15:12 +00002097}
Douglas Gregord3022602009-03-27 23:10:48 +00002098
2099Sema::TypeResult
2100Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
2101 const IdentifierInfo &II, SourceLocation IdLoc) {
2102 NestedNameSpecifier *NNS
2103 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
2104 if (!NNS)
2105 return true;
2106
2107 QualType T = CheckTypenameType(NNS, II, SourceRange(TypenameLoc, IdLoc));
Douglas Gregord7cb0372009-04-01 21:51:26 +00002108 if (T.isNull())
2109 return true;
Douglas Gregord3022602009-03-27 23:10:48 +00002110 return T.getAsOpaquePtr();
2111}
2112
Douglas Gregor77da5802009-04-01 00:28:59 +00002113Sema::TypeResult
2114Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
2115 SourceLocation TemplateLoc, TypeTy *Ty) {
2116 QualType T = QualType::getFromOpaquePtr(Ty);
2117 NestedNameSpecifier *NNS
2118 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
2119 const TemplateSpecializationType *TemplateId
2120 = T->getAsTemplateSpecializationType();
2121 assert(TemplateId && "Expected a template specialization type");
2122
2123 if (NNS->isDependent())
2124 return Context.getTypenameType(NNS, TemplateId).getAsOpaquePtr();
2125
2126 return Context.getQualifiedNameType(NNS, T).getAsOpaquePtr();
2127}
2128
Douglas Gregord3022602009-03-27 23:10:48 +00002129/// \brief Build the type that describes a C++ typename specifier,
2130/// e.g., "typename T::type".
2131QualType
2132Sema::CheckTypenameType(NestedNameSpecifier *NNS, const IdentifierInfo &II,
2133 SourceRange Range) {
2134 if (NNS->isDependent()) // FIXME: member of the current instantiation!
2135 return Context.getTypenameType(NNS, &II);
2136
2137 CXXScopeSpec SS;
2138 SS.setScopeRep(NNS);
2139 SS.setRange(Range);
2140 if (RequireCompleteDeclContext(SS))
2141 return QualType();
2142
2143 DeclContext *Ctx = computeDeclContext(SS);
2144 assert(Ctx && "No declaration context?");
2145
2146 DeclarationName Name(&II);
2147 LookupResult Result = LookupQualifiedName(Ctx, Name, LookupOrdinaryName,
2148 false);
2149 unsigned DiagID = 0;
2150 Decl *Referenced = 0;
2151 switch (Result.getKind()) {
2152 case LookupResult::NotFound:
2153 if (Ctx->isTranslationUnit())
2154 DiagID = diag::err_typename_nested_not_found_global;
2155 else
2156 DiagID = diag::err_typename_nested_not_found;
2157 break;
2158
2159 case LookupResult::Found:
2160 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getAsDecl())) {
2161 // We found a type. Build a QualifiedNameType, since the
2162 // typename-specifier was just sugar. FIXME: Tell
2163 // QualifiedNameType that it has a "typename" prefix.
2164 return Context.getQualifiedNameType(NNS, Context.getTypeDeclType(Type));
2165 }
2166
2167 DiagID = diag::err_typename_nested_not_type;
2168 Referenced = Result.getAsDecl();
2169 break;
2170
2171 case LookupResult::FoundOverloaded:
2172 DiagID = diag::err_typename_nested_not_type;
2173 Referenced = *Result.begin();
2174 break;
2175
2176 case LookupResult::AmbiguousBaseSubobjectTypes:
2177 case LookupResult::AmbiguousBaseSubobjects:
2178 case LookupResult::AmbiguousReference:
2179 DiagnoseAmbiguousLookup(Result, Name, Range.getEnd(), Range);
2180 return QualType();
2181 }
2182
2183 // If we get here, it's because name lookup did not find a
2184 // type. Emit an appropriate diagnostic and return an error.
2185 if (NamedDecl *NamedCtx = dyn_cast<NamedDecl>(Ctx))
2186 Diag(Range.getEnd(), DiagID) << Range << Name << NamedCtx;
2187 else
2188 Diag(Range.getEnd(), DiagID) << Range << Name;
2189 if (Referenced)
2190 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
2191 << Name;
2192 return QualType();
2193}