blob: 43713e11f18c6831872bfae6db57197af146f261 [file] [log] [blame]
Douglas Gregor72c3f312008-12-05 18:15:24 +00001//===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===/
2
3//
4// The LLVM Compiler Infrastructure
5//
6// This file is distributed under the University of Illinois Open Source
7// License. See LICENSE.TXT for details.
Douglas Gregor99ebf652009-02-27 19:31:52 +00008//===----------------------------------------------------------------------===/
Douglas Gregor72c3f312008-12-05 18:15:24 +00009
10//
11// This file implements semantic analysis for C++ templates.
Douglas Gregor99ebf652009-02-27 19:31:52 +000012//===----------------------------------------------------------------------===/
Douglas Gregor72c3f312008-12-05 18:15:24 +000013
14#include "Sema.h"
Douglas Gregorddc29e12009-02-06 22:42:48 +000015#include "clang/AST/ASTContext.h"
Douglas Gregor898574e2008-12-05 23:32:09 +000016#include "clang/AST/Expr.h"
Douglas Gregorcc45cb32009-02-11 19:52:55 +000017#include "clang/AST/ExprCXX.h"
Douglas Gregoraaba5e32009-02-04 19:02:06 +000018#include "clang/AST/DeclTemplate.h"
Douglas Gregor72c3f312008-12-05 18:15:24 +000019#include "clang/Parse/DeclSpec.h"
20#include "clang/Basic/LangOptions.h"
21
22using namespace clang;
23
Douglas Gregord6fb7ef2008-12-18 19:37:40 +000024/// isTemplateName - Determines whether the identifier II is a
25/// template name in the current scope, and returns the template
26/// declaration if II names a template. An optional CXXScope can be
27/// passed to indicate the C++ scope in which the identifier will be
28/// found.
Douglas Gregorc45c2322009-03-31 00:43:58 +000029TemplateNameKind Sema::isTemplateName(const IdentifierInfo &II, Scope *S,
Douglas Gregor7532dc62009-03-30 22:58:21 +000030 TemplateTy &TemplateResult,
Douglas Gregor39a8de12009-02-25 19:37:18 +000031 const CXXScopeSpec *SS) {
Douglas Gregor47b9a1c2009-02-04 17:27:36 +000032 NamedDecl *IIDecl = LookupParsedName(S, SS, &II, LookupOrdinaryName);
Douglas Gregord6fb7ef2008-12-18 19:37:40 +000033
Douglas Gregor7532dc62009-03-30 22:58:21 +000034 TemplateNameKind TNK = TNK_Non_template;
35 TemplateDecl *Template = 0;
36
Douglas Gregord6fb7ef2008-12-18 19:37:40 +000037 if (IIDecl) {
Douglas Gregor7532dc62009-03-30 22:58:21 +000038 if ((Template = dyn_cast<TemplateDecl>(IIDecl))) {
Douglas Gregor55f6b142009-02-09 18:46:07 +000039 if (isa<FunctionTemplateDecl>(IIDecl))
Douglas Gregor7532dc62009-03-30 22:58:21 +000040 TNK = TNK_Function_template;
Douglas Gregorc45c2322009-03-31 00:43:58 +000041 else if (isa<ClassTemplateDecl>(IIDecl) ||
42 isa<TemplateTemplateParmDecl>(IIDecl))
43 TNK = TNK_Type_template;
Douglas Gregor7532dc62009-03-30 22:58:21 +000044 else
45 assert(false && "Unknown template declaration kind");
Douglas Gregorbefc20e2009-03-26 00:10:35 +000046 } else if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(IIDecl)) {
47 // C++ [temp.local]p1:
48 // Like normal (non-template) classes, class templates have an
49 // injected-class-name (Clause 9). The injected-class-name
50 // can be used with or without a template-argument-list. When
51 // it is used without a template-argument-list, it is
52 // equivalent to the injected-class-name followed by the
53 // template-parameters of the class template enclosed in
54 // <>. When it is used with a template-argument-list, it
55 // refers to the specified class template specialization,
56 // which could be the current specialization or another
57 // specialization.
58 if (Record->isInjectedClassName()) {
59 Record = cast<CXXRecordDecl>(Context.getCanonicalDecl(Record));
Douglas Gregor7532dc62009-03-30 22:58:21 +000060 if ((Template = Record->getDescribedClassTemplate()))
Douglas Gregorc45c2322009-03-31 00:43:58 +000061 TNK = TNK_Type_template;
Douglas Gregor7532dc62009-03-30 22:58:21 +000062 else if (ClassTemplateSpecializationDecl *Spec
Douglas Gregorbefc20e2009-03-26 00:10:35 +000063 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
Douglas Gregor7532dc62009-03-30 22:58:21 +000064 Template = Spec->getSpecializedTemplate();
Douglas Gregorc45c2322009-03-31 00:43:58 +000065 TNK = TNK_Type_template;
Douglas Gregorbefc20e2009-03-26 00:10:35 +000066 }
67 }
Douglas Gregor55f6b142009-02-09 18:46:07 +000068 }
Douglas Gregoraaba5e32009-02-04 19:02:06 +000069
Douglas Gregor55f6b142009-02-09 18:46:07 +000070 // FIXME: What follows is a gross hack.
Douglas Gregord6fb7ef2008-12-18 19:37:40 +000071 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(IIDecl)) {
Douglas Gregor55f6b142009-02-09 18:46:07 +000072 if (FD->getType()->isDependentType()) {
Douglas Gregor7532dc62009-03-30 22:58:21 +000073 TemplateResult = TemplateTy::make(FD);
Douglas Gregor55f6b142009-02-09 18:46:07 +000074 return TNK_Function_template;
75 }
Douglas Gregord6fb7ef2008-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 Gregor55f6b142009-02-09 18:46:07 +000081 if ((*F)->getType()->isDependentType()) {
Douglas Gregor7532dc62009-03-30 22:58:21 +000082 TemplateResult = TemplateTy::make(Ovl);
Douglas Gregor55f6b142009-02-09 18:46:07 +000083 return TNK_Function_template;
84 }
Douglas Gregord6fb7ef2008-12-18 19:37:40 +000085 }
86 }
Douglas Gregor7532dc62009-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 Gregord6fb7ef2008-12-18 19:37:40 +000099 }
Douglas Gregor7532dc62009-03-30 22:58:21 +0000100 return TNK;
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000101}
102
Douglas Gregor72c3f312008-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 Gregorf57172b2008-12-08 18:40:42 +0000108 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregor72c3f312008-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 Gregor2943aed2009-03-03 04:44:36 +0000123/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregoraaba5e32009-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 Lattnerb28317a2009-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 Gregoraaba5e32009-02-04 19:02:06 +0000129 return Temp;
130 }
131 return 0;
132}
133
Douglas Gregor72c3f312008-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 Lattnerb28317a2009-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 Gregor72c3f312008-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 Gregor47b9a1c2009-02-04 17:27:36 +0000153 NamedDecl *PrevDecl = LookupName(S, ParamName, LookupTagName);
Douglas Gregorf57172b2008-12-08 18:40:42 +0000154 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor72c3f312008-12-05 18:15:24 +0000155 Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc,
156 PrevDecl);
157 }
158
Douglas Gregorddc29e12009-02-06 22:42:48 +0000159 SourceLocation Loc = ParamNameLoc;
160 if (!ParamName)
161 Loc = KeyLoc;
162
Douglas Gregor72c3f312008-12-05 18:15:24 +0000163 TemplateTypeParmDecl *Param
Douglas Gregorddc29e12009-02-06 22:42:48 +0000164 = TemplateTypeParmDecl::Create(Context, CurContext, Loc,
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000165 Depth, Position, ParamName, Typename);
Douglas Gregor72c3f312008-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 Lattnerb28317a2009-03-28 19:18:32 +0000171 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor72c3f312008-12-05 18:15:24 +0000172 IdResolver.AddDecl(Param);
173 }
174
Chris Lattnerb28317a2009-03-28 19:18:32 +0000175 return DeclPtrTy::make(Param);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000176}
177
Douglas Gregord684b002009-02-10 19:49:53 +0000178/// ActOnTypeParameterDefault - Adds a default argument (the type
179/// Default) to the given template type parameter (TypeParam).
Chris Lattnerb28317a2009-03-28 19:18:32 +0000180void Sema::ActOnTypeParameterDefault(DeclPtrTy TypeParam,
Douglas Gregord684b002009-02-10 19:49:53 +0000181 SourceLocation EqualLoc,
182 SourceLocation DefaultLoc,
183 TypeTy *DefaultT) {
184 TemplateTypeParmDecl *Parm
Chris Lattnerb28317a2009-03-28 19:18:32 +0000185 = cast<TemplateTypeParmDecl>(TypeParam.getAs<Decl>());
Douglas Gregord684b002009-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 Gregor2943aed2009-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 Gregor72c3f312008-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 Lattnerb28317a2009-03-28 19:18:32 +0000249Sema::DeclPtrTy Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
250 unsigned Depth,
251 unsigned Position) {
Douglas Gregor72c3f312008-12-05 18:15:24 +0000252 QualType T = GetTypeForDeclarator(D, S);
253
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000254 assert(S->isTemplateParamScope() &&
255 "Non-type template parameter not in template parameter scope!");
Douglas Gregor72c3f312008-12-05 18:15:24 +0000256 bool Invalid = false;
257
258 IdentifierInfo *ParamName = D.getIdentifier();
259 if (ParamName) {
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000260 NamedDecl *PrevDecl = LookupName(S, ParamName, LookupTagName);
Douglas Gregorf57172b2008-12-08 18:40:42 +0000261 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor72c3f312008-12-05 18:15:24 +0000262 Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000263 PrevDecl);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000264 }
265
Douglas Gregor2943aed2009-03-03 04:44:36 +0000266 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
Douglas Gregorceef30c2009-03-09 16:46:39 +0000267 if (T.isNull()) {
Douglas Gregor2943aed2009-03-03 04:44:36 +0000268 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregorceef30c2009-03-09 16:46:39 +0000269 Invalid = true;
270 }
Douglas Gregor5d290d52009-02-10 17:43:50 +0000271
Douglas Gregor72c3f312008-12-05 18:15:24 +0000272 NonTypeTemplateParmDecl *Param
273 = NonTypeTemplateParmDecl::Create(Context, CurContext, D.getIdentifierLoc(),
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000274 Depth, Position, ParamName, T);
Douglas Gregor72c3f312008-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 Lattnerb28317a2009-03-28 19:18:32 +0000280 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor72c3f312008-12-05 18:15:24 +0000281 IdResolver.AddDecl(Param);
282 }
Chris Lattnerb28317a2009-03-28 19:18:32 +0000283 return DeclPtrTy::make(Param);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000284}
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000285
Douglas Gregord684b002009-02-10 19:49:53 +0000286/// \brief Adds a default argument to the given non-type template
287/// parameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000288void Sema::ActOnNonTypeTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregord684b002009-02-10 19:49:53 +0000289 SourceLocation EqualLoc,
290 ExprArg DefaultE) {
291 NonTypeTemplateParmDecl *TemplateParm
Chris Lattnerb28317a2009-03-28 19:18:32 +0000292 = cast<NonTypeTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregord684b002009-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 Gregor2943aed2009-03-03 04:44:36 +0000300 if (CheckTemplateArgument(TemplateParm, TemplateParm->getType(), Default)) {
Douglas Gregord684b002009-02-10 19:49:53 +0000301 TemplateParm->setInvalidDecl();
302 return;
303 }
304
Anders Carlssone9146f22009-05-01 19:49:17 +0000305 TemplateParm->setDefaultArgument(DefaultE.takeAs<Expr>());
Douglas Gregord684b002009-02-10 19:49:53 +0000306}
307
Douglas Gregoraaba5e32009-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 Lattnerb28317a2009-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 Gregoraaba5e32009-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 Lattnerb28317a2009-03-28 19:18:32 +0000341 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000342 IdResolver.AddDecl(Param);
343 }
344
Chris Lattnerb28317a2009-03-28 19:18:32 +0000345 return DeclPtrTy::make(Param);
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000346}
347
Douglas Gregord684b002009-02-10 19:49:53 +0000348/// \brief Adds a default argument to the given template template
349/// parameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000350void Sema::ActOnTemplateTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregord684b002009-02-10 19:49:53 +0000351 SourceLocation EqualLoc,
352 ExprArg DefaultE) {
353 TemplateTemplateParmDecl *TemplateParm
Chris Lattnerb28317a2009-03-28 19:18:32 +0000354 = cast<TemplateTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregord684b002009-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 Gregorc4b4e7b2008-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 Lattnerb28317a2009-03-28 19:18:32 +0000389 DeclPtrTy *Params, unsigned NumParams,
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000390 SourceLocation RAngleLoc) {
391 if (ExportLoc.isValid())
392 Diag(ExportLoc, diag::note_template_export_unsupported);
393
Douglas Gregorddc29e12009-02-06 22:42:48 +0000394 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
395 (Decl**)Params, NumParams, RAngleLoc);
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000396}
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000397
Douglas Gregor212e81c2009-03-25 00:13:59 +0000398Sema::DeclResult
Douglas Gregorddc29e12009-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 Carlsson5aeccdb2009-03-26 00:52:18 +0000403 MultiTemplateParamsArg TemplateParameterLists,
404 AccessSpecifier AS) {
Douglas Gregorddc29e12009-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 Gregord684b002009-02-10 19:49:53 +0000407 bool Invalid = false;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000408
409 // Check that we can declare a template here.
410 if (CheckTemplateDeclScope(S, TemplateParameterLists))
Douglas Gregor212e81c2009-03-25 00:13:59 +0000411 return true;
Douglas Gregorddc29e12009-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 Gregor212e81c2009-03-25 00:13:59 +0000424 return true;
Douglas Gregorddc29e12009-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 Gregore4e5b052009-03-19 00:18:19 +0000437 SemanticContext = computeDeclContext(SS);
Douglas Gregorddc29e12009-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 Gregor212e81c2009-03-25 00:13:59 +0000456 return true;
Douglas Gregorddc29e12009-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) {
Douglas Gregora3a83512009-04-01 23:51:29 +0000465 Diag(KWLoc, diag::err_use_with_wrong_tag)
466 << Name
467 << CodeModificationHint::CreateReplacement(KWLoc,
468 PrevRecordDecl->getKindName());
Douglas Gregorddc29e12009-02-06 22:42:48 +0000469 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregora3a83512009-04-01 23:51:29 +0000470 Kind = PrevRecordDecl->getTagKind();
Douglas Gregorddc29e12009-02-06 22:42:48 +0000471 }
472
Douglas Gregorddc29e12009-02-06 22:42:48 +0000473 // Check for redefinition of this class template.
474 if (TK == TK_Definition) {
475 if (TagDecl *Def = PrevRecordDecl->getDefinition(Context)) {
476 Diag(NameLoc, diag::err_redefinition) << Name;
477 Diag(Def->getLocation(), diag::note_previous_definition);
478 // FIXME: Would it make sense to try to "forget" the previous
479 // definition, as part of error recovery?
Douglas Gregor212e81c2009-03-25 00:13:59 +0000480 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000481 }
482 }
483 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
484 // Maybe we will complain about the shadowed template parameter.
485 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
486 // Just pretend that we didn't see the previous declaration.
487 PrevDecl = 0;
488 } else if (PrevDecl) {
489 // C++ [temp]p5:
490 // A class template shall not have the same name as any other
491 // template, class, function, object, enumeration, enumerator,
492 // namespace, or type in the same scope (3.3), except as specified
493 // in (14.5.4).
494 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
495 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor212e81c2009-03-25 00:13:59 +0000496 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000497 }
498
Douglas Gregord684b002009-02-10 19:49:53 +0000499 // Check the template parameter list of this declaration, possibly
500 // merging in the template parameter list from the previous class
501 // template declaration.
502 if (CheckTemplateParameterList(TemplateParams,
503 PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0))
504 Invalid = true;
505
Douglas Gregorddc29e12009-02-06 22:42:48 +0000506 // If we had a scope specifier, we better have a previous template
507 // declaration!
508
Douglas Gregorbefc20e2009-03-26 00:10:35 +0000509 CXXRecordDecl *NewClass =
Douglas Gregorddc29e12009-02-06 22:42:48 +0000510 CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name,
511 PrevClassTemplate?
512 PrevClassTemplate->getTemplatedDecl() : 0);
513
514 ClassTemplateDecl *NewTemplate
515 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
516 DeclarationName(Name), TemplateParams,
Douglas Gregor5953d8b2009-03-19 17:26:29 +0000517 NewClass, PrevClassTemplate);
Douglas Gregorbefc20e2009-03-26 00:10:35 +0000518 NewClass->setDescribedClassTemplate(NewTemplate);
519
Anders Carlsson4cbe82c2009-03-26 01:24:28 +0000520 // Set the access specifier.
521 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
522
Douglas Gregorddc29e12009-02-06 22:42:48 +0000523 // Set the lexical context of these templates
524 NewClass->setLexicalDeclContext(CurContext);
525 NewTemplate->setLexicalDeclContext(CurContext);
526
527 if (TK == TK_Definition)
528 NewClass->startDefinition();
529
530 if (Attr)
531 ProcessDeclAttributeList(NewClass, Attr);
532
533 PushOnScopeChains(NewTemplate, S);
534
Douglas Gregord684b002009-02-10 19:49:53 +0000535 if (Invalid) {
536 NewTemplate->setInvalidDecl();
537 NewClass->setInvalidDecl();
538 }
Chris Lattnerb28317a2009-03-28 19:18:32 +0000539 return DeclPtrTy::make(NewTemplate);
Douglas Gregorddc29e12009-02-06 22:42:48 +0000540}
541
Douglas Gregord684b002009-02-10 19:49:53 +0000542/// \brief Checks the validity of a template parameter list, possibly
543/// considering the template parameter list from a previous
544/// declaration.
545///
546/// If an "old" template parameter list is provided, it must be
547/// equivalent (per TemplateParameterListsAreEqual) to the "new"
548/// template parameter list.
549///
550/// \param NewParams Template parameter list for a new template
551/// declaration. This template parameter list will be updated with any
552/// default arguments that are carried through from the previous
553/// template parameter list.
554///
555/// \param OldParams If provided, template parameter list from a
556/// previous declaration of the same template. Default template
557/// arguments will be merged from the old template parameter list to
558/// the new template parameter list.
559///
560/// \returns true if an error occurred, false otherwise.
561bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
562 TemplateParameterList *OldParams) {
563 bool Invalid = false;
564
565 // C++ [temp.param]p10:
566 // The set of default template-arguments available for use with a
567 // template declaration or definition is obtained by merging the
568 // default arguments from the definition (if in scope) and all
569 // declarations in scope in the same way default function
570 // arguments are (8.3.6).
571 bool SawDefaultArgument = false;
572 SourceLocation PreviousDefaultArgLoc;
Douglas Gregorc15cb382009-02-09 23:23:08 +0000573
Mike Stump1a35fde2009-02-11 23:03:27 +0000574 // Dummy initialization to avoid warnings.
Douglas Gregor1bc69132009-02-11 20:46:19 +0000575 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregord684b002009-02-10 19:49:53 +0000576 if (OldParams)
577 OldParam = OldParams->begin();
578
579 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
580 NewParamEnd = NewParams->end();
581 NewParam != NewParamEnd; ++NewParam) {
582 // Variables used to diagnose redundant default arguments
583 bool RedundantDefaultArg = false;
584 SourceLocation OldDefaultLoc;
585 SourceLocation NewDefaultLoc;
586
587 // Variables used to diagnose missing default arguments
588 bool MissingDefaultArg = false;
589
590 // Merge default arguments for template type parameters.
591 if (TemplateTypeParmDecl *NewTypeParm
592 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
593 TemplateTypeParmDecl *OldTypeParm
594 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
595
596 if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
597 NewTypeParm->hasDefaultArgument()) {
598 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
599 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
600 SawDefaultArgument = true;
601 RedundantDefaultArg = true;
602 PreviousDefaultArgLoc = NewDefaultLoc;
603 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
604 // Merge the default argument from the old declaration to the
605 // new declaration.
606 SawDefaultArgument = true;
607 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgument(),
608 OldTypeParm->getDefaultArgumentLoc(),
609 true);
610 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
611 } else if (NewTypeParm->hasDefaultArgument()) {
612 SawDefaultArgument = true;
613 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
614 } else if (SawDefaultArgument)
615 MissingDefaultArg = true;
616 }
617 // Merge default arguments for non-type template parameters
618 else if (NonTypeTemplateParmDecl *NewNonTypeParm
619 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
620 NonTypeTemplateParmDecl *OldNonTypeParm
621 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
622 if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
623 NewNonTypeParm->hasDefaultArgument()) {
624 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
625 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
626 SawDefaultArgument = true;
627 RedundantDefaultArg = true;
628 PreviousDefaultArgLoc = NewDefaultLoc;
629 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
630 // Merge the default argument from the old declaration to the
631 // new declaration.
632 SawDefaultArgument = true;
633 // FIXME: We need to create a new kind of "default argument"
634 // expression that points to a previous template template
635 // parameter.
636 NewNonTypeParm->setDefaultArgument(
637 OldNonTypeParm->getDefaultArgument());
638 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
639 } else if (NewNonTypeParm->hasDefaultArgument()) {
640 SawDefaultArgument = true;
641 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
642 } else if (SawDefaultArgument)
643 MissingDefaultArg = true;
644 }
645 // Merge default arguments for template template parameters
646 else {
647 TemplateTemplateParmDecl *NewTemplateParm
648 = cast<TemplateTemplateParmDecl>(*NewParam);
649 TemplateTemplateParmDecl *OldTemplateParm
650 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
651 if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
652 NewTemplateParm->hasDefaultArgument()) {
653 OldDefaultLoc = OldTemplateParm->getDefaultArgumentLoc();
654 NewDefaultLoc = NewTemplateParm->getDefaultArgumentLoc();
655 SawDefaultArgument = true;
656 RedundantDefaultArg = true;
657 PreviousDefaultArgLoc = NewDefaultLoc;
658 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
659 // Merge the default argument from the old declaration to the
660 // new declaration.
661 SawDefaultArgument = true;
662 // FIXME: We need to create a new kind of "default argument"
663 // expression that points to a previous template template
664 // parameter.
665 NewTemplateParm->setDefaultArgument(
666 OldTemplateParm->getDefaultArgument());
667 PreviousDefaultArgLoc = OldTemplateParm->getDefaultArgumentLoc();
668 } else if (NewTemplateParm->hasDefaultArgument()) {
669 SawDefaultArgument = true;
670 PreviousDefaultArgLoc = NewTemplateParm->getDefaultArgumentLoc();
671 } else if (SawDefaultArgument)
672 MissingDefaultArg = true;
673 }
674
675 if (RedundantDefaultArg) {
676 // C++ [temp.param]p12:
677 // A template-parameter shall not be given default arguments
678 // by two different declarations in the same scope.
679 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
680 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
681 Invalid = true;
682 } else if (MissingDefaultArg) {
683 // C++ [temp.param]p11:
684 // If a template-parameter has a default template-argument,
685 // all subsequent template-parameters shall have a default
686 // template-argument supplied.
687 Diag((*NewParam)->getLocation(),
688 diag::err_template_param_default_arg_missing);
689 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
690 Invalid = true;
691 }
692
693 // If we have an old template parameter list that we're merging
694 // in, move on to the next parameter.
695 if (OldParams)
696 ++OldParam;
697 }
698
699 return Invalid;
700}
Douglas Gregorc15cb382009-02-09 23:23:08 +0000701
Douglas Gregor40808ce2009-03-09 23:48:35 +0000702/// \brief Translates template arguments as provided by the parser
703/// into template arguments used by semantic analysis.
704static void
705translateTemplateArguments(ASTTemplateArgsPtr &TemplateArgsIn,
706 SourceLocation *TemplateArgLocs,
707 llvm::SmallVector<TemplateArgument, 16> &TemplateArgs) {
708 TemplateArgs.reserve(TemplateArgsIn.size());
709
710 void **Args = TemplateArgsIn.getArgs();
711 bool *ArgIsType = TemplateArgsIn.getArgIsType();
712 for (unsigned Arg = 0, Last = TemplateArgsIn.size(); Arg != Last; ++Arg) {
713 TemplateArgs.push_back(
714 ArgIsType[Arg]? TemplateArgument(TemplateArgLocs[Arg],
715 QualType::getFromOpaquePtr(Args[Arg]))
716 : TemplateArgument(reinterpret_cast<Expr *>(Args[Arg])));
717 }
718}
719
Douglas Gregorc45c2322009-03-31 00:43:58 +0000720/// \brief Build a canonical version of a template argument list.
721///
722/// This function builds a canonical version of the given template
723/// argument list, where each of the template arguments has been
724/// converted into its canonical form. This routine is typically used
725/// to canonicalize a template argument list when the template name
726/// itself is dependent. When the template name refers to an actual
727/// template declaration, Sema::CheckTemplateArgumentList should be
728/// used to check and canonicalize the template arguments.
729///
730/// \param TemplateArgs The incoming template arguments.
731///
732/// \param NumTemplateArgs The number of template arguments in \p
733/// TemplateArgs.
734///
735/// \param Canonical A vector to be filled with the canonical versions
736/// of the template arguments.
737///
738/// \param Context The ASTContext in which the template arguments live.
739static void CanonicalizeTemplateArguments(const TemplateArgument *TemplateArgs,
740 unsigned NumTemplateArgs,
741 llvm::SmallVectorImpl<TemplateArgument> &Canonical,
742 ASTContext &Context) {
743 Canonical.reserve(NumTemplateArgs);
744 for (unsigned Idx = 0; Idx < NumTemplateArgs; ++Idx) {
745 switch (TemplateArgs[Idx].getKind()) {
746 case TemplateArgument::Expression:
747 // FIXME: Build canonical expression (!)
748 Canonical.push_back(TemplateArgs[Idx]);
749 break;
750
751 case TemplateArgument::Declaration:
752 Canonical.push_back(TemplateArgument(SourceLocation(),
753 TemplateArgs[Idx].getAsDecl()));
754 break;
755
756 case TemplateArgument::Integral:
757 Canonical.push_back(TemplateArgument(SourceLocation(),
758 *TemplateArgs[Idx].getAsIntegral(),
759 TemplateArgs[Idx].getIntegralType()));
760
761 case TemplateArgument::Type: {
762 QualType CanonType
763 = Context.getCanonicalType(TemplateArgs[Idx].getAsType());
764 Canonical.push_back(TemplateArgument(SourceLocation(), CanonType));
765 }
766 }
767 }
768}
769
Douglas Gregor7532dc62009-03-30 22:58:21 +0000770QualType Sema::CheckTemplateIdType(TemplateName Name,
771 SourceLocation TemplateLoc,
772 SourceLocation LAngleLoc,
773 const TemplateArgument *TemplateArgs,
774 unsigned NumTemplateArgs,
775 SourceLocation RAngleLoc) {
776 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregorc45c2322009-03-31 00:43:58 +0000777 if (!Template) {
778 // The template name does not resolve to a template, so we just
779 // build a dependent template-id type.
780
781 // Canonicalize the template arguments to build the canonical
782 // template-id type.
783 llvm::SmallVector<TemplateArgument, 16> CanonicalTemplateArgs;
784 CanonicalizeTemplateArguments(TemplateArgs, NumTemplateArgs,
785 CanonicalTemplateArgs, Context);
786
787 // FIXME: Get the canonical template-name
788 QualType CanonType
789 = Context.getTemplateSpecializationType(Name, &CanonicalTemplateArgs[0],
790 CanonicalTemplateArgs.size());
791
792 // Build the dependent template-id type.
793 return Context.getTemplateSpecializationType(Name, TemplateArgs,
794 NumTemplateArgs, CanonType);
795 }
Douglas Gregor7532dc62009-03-30 22:58:21 +0000796
Douglas Gregor40808ce2009-03-09 23:48:35 +0000797 // Check that the template argument list is well-formed for this
798 // template.
799 llvm::SmallVector<TemplateArgument, 16> ConvertedTemplateArgs;
Douglas Gregor7532dc62009-03-30 22:58:21 +0000800 if (CheckTemplateArgumentList(Template, TemplateLoc, LAngleLoc,
Douglas Gregor40808ce2009-03-09 23:48:35 +0000801 TemplateArgs, NumTemplateArgs, RAngleLoc,
802 ConvertedTemplateArgs))
803 return QualType();
804
805 assert((ConvertedTemplateArgs.size() ==
Douglas Gregor7532dc62009-03-30 22:58:21 +0000806 Template->getTemplateParameters()->size()) &&
Douglas Gregor40808ce2009-03-09 23:48:35 +0000807 "Converted template argument list is too short!");
808
809 QualType CanonType;
810
Douglas Gregor7532dc62009-03-30 22:58:21 +0000811 if (TemplateSpecializationType::anyDependentTemplateArguments(
Douglas Gregor40808ce2009-03-09 23:48:35 +0000812 TemplateArgs,
813 NumTemplateArgs)) {
814 // This class template specialization is a dependent
815 // type. Therefore, its canonical type is another class template
816 // specialization type that contains all of the converted
817 // arguments in canonical form. This ensures that, e.g., A<T> and
818 // A<T, T> have identical types when A is declared as:
819 //
820 // template<typename T, typename U = T> struct A;
821
Douglas Gregor7532dc62009-03-30 22:58:21 +0000822 CanonType = Context.getTemplateSpecializationType(Name,
Douglas Gregor40808ce2009-03-09 23:48:35 +0000823 &ConvertedTemplateArgs[0],
824 ConvertedTemplateArgs.size());
Douglas Gregor7532dc62009-03-30 22:58:21 +0000825 } else if (ClassTemplateDecl *ClassTemplate
826 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregor40808ce2009-03-09 23:48:35 +0000827 // Find the class template specialization declaration that
828 // corresponds to these arguments.
829 llvm::FoldingSetNodeID ID;
830 ClassTemplateSpecializationDecl::Profile(ID, &ConvertedTemplateArgs[0],
831 ConvertedTemplateArgs.size());
832 void *InsertPos = 0;
833 ClassTemplateSpecializationDecl *Decl
834 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
835 if (!Decl) {
836 // This is the first time we have referenced this class template
837 // specialization. Create the canonical declaration and add it to
838 // the set of specializations.
839 Decl = ClassTemplateSpecializationDecl::Create(Context,
840 ClassTemplate->getDeclContext(),
841 TemplateLoc,
842 ClassTemplate,
843 &ConvertedTemplateArgs[0],
844 ConvertedTemplateArgs.size(),
845 0);
846 ClassTemplate->getSpecializations().InsertNode(Decl, InsertPos);
847 Decl->setLexicalDeclContext(CurContext);
848 }
849
850 CanonType = Context.getTypeDeclType(Decl);
851 }
852
853 // Build the fully-sugared type for this class template
854 // specialization, which refers back to the class template
855 // specialization we created or found.
Douglas Gregor7532dc62009-03-30 22:58:21 +0000856 return Context.getTemplateSpecializationType(Name, TemplateArgs,
857 NumTemplateArgs, CanonType);
Douglas Gregor40808ce2009-03-09 23:48:35 +0000858}
859
Douglas Gregorcc636682009-02-17 23:15:12 +0000860Action::TypeResult
Douglas Gregor7532dc62009-03-30 22:58:21 +0000861Sema::ActOnTemplateIdType(TemplateTy TemplateD, SourceLocation TemplateLoc,
862 SourceLocation LAngleLoc,
863 ASTTemplateArgsPtr TemplateArgsIn,
864 SourceLocation *TemplateArgLocs,
865 SourceLocation RAngleLoc) {
866 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Douglas Gregor55f6b142009-02-09 18:46:07 +0000867
Douglas Gregor40808ce2009-03-09 23:48:35 +0000868 // Translate the parser's template argument list in our AST format.
869 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
870 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
Douglas Gregorc15cb382009-02-09 23:23:08 +0000871
Douglas Gregor7532dc62009-03-30 22:58:21 +0000872 QualType Result = CheckTemplateIdType(Template, TemplateLoc, LAngleLoc,
873 &TemplateArgs[0], TemplateArgs.size(),
874 RAngleLoc);
Douglas Gregor40808ce2009-03-09 23:48:35 +0000875 TemplateArgsIn.release();
Douglas Gregor31a19b62009-04-01 21:51:26 +0000876
877 if (Result.isNull())
878 return true;
879
Douglas Gregor5908e9f2009-02-09 19:34:22 +0000880 return Result.getAsOpaquePtr();
Douglas Gregor55f6b142009-02-09 18:46:07 +0000881}
882
Douglas Gregorc45c2322009-03-31 00:43:58 +0000883/// \brief Form a dependent template name.
884///
885/// This action forms a dependent template name given the template
886/// name and its (presumably dependent) scope specifier. For
887/// example, given "MetaFun::template apply", the scope specifier \p
888/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
889/// of the "template" keyword, and "apply" is the \p Name.
890Sema::TemplateTy
891Sema::ActOnDependentTemplateName(SourceLocation TemplateKWLoc,
892 const IdentifierInfo &Name,
893 SourceLocation NameLoc,
894 const CXXScopeSpec &SS) {
895 if (!SS.isSet() || SS.isInvalid())
896 return TemplateTy();
897
898 NestedNameSpecifier *Qualifier
899 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
900
901 // FIXME: member of the current instantiation
902
903 if (!Qualifier->isDependent()) {
904 // C++0x [temp.names]p5:
905 // If a name prefixed by the keyword template is not the name of
906 // a template, the program is ill-formed. [Note: the keyword
907 // template may not be applied to non-template members of class
908 // templates. -end note ] [ Note: as is the case with the
909 // typename prefix, the template prefix is allowed in cases
910 // where it is not strictly necessary; i.e., when the
911 // nested-name-specifier or the expression on the left of the ->
912 // or . is not dependent on a template-parameter, or the use
913 // does not appear in the scope of a template. -end note]
914 //
915 // Note: C++03 was more strict here, because it banned the use of
916 // the "template" keyword prior to a template-name that was not a
917 // dependent name. C++ DR468 relaxed this requirement (the
918 // "template" keyword is now permitted). We follow the C++0x
919 // rules, even in C++03 mode, retroactively applying the DR.
920 TemplateTy Template;
921 TemplateNameKind TNK = isTemplateName(Name, 0, Template, &SS);
922 if (TNK == TNK_Non_template) {
923 Diag(NameLoc, diag::err_template_kw_refers_to_non_template)
924 << &Name;
925 return TemplateTy();
926 }
927
928 return Template;
929 }
930
931 return TemplateTy::make(Context.getDependentTemplateName(Qualifier, &Name));
932}
933
Douglas Gregorc15cb382009-02-09 23:23:08 +0000934/// \brief Check that the given template argument list is well-formed
935/// for specializing the given template.
936bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
937 SourceLocation TemplateLoc,
938 SourceLocation LAngleLoc,
Douglas Gregor40808ce2009-03-09 23:48:35 +0000939 const TemplateArgument *TemplateArgs,
940 unsigned NumTemplateArgs,
Douglas Gregor3e00bad2009-02-17 01:05:43 +0000941 SourceLocation RAngleLoc,
942 llvm::SmallVectorImpl<TemplateArgument> &Converted) {
Douglas Gregorc15cb382009-02-09 23:23:08 +0000943 TemplateParameterList *Params = Template->getTemplateParameters();
944 unsigned NumParams = Params->size();
Douglas Gregor40808ce2009-03-09 23:48:35 +0000945 unsigned NumArgs = NumTemplateArgs;
Douglas Gregorc15cb382009-02-09 23:23:08 +0000946 bool Invalid = false;
947
948 if (NumArgs > NumParams ||
Douglas Gregor62cb18d2009-02-11 18:16:40 +0000949 NumArgs < Params->getMinRequiredArguments()) {
Douglas Gregorc15cb382009-02-09 23:23:08 +0000950 // FIXME: point at either the first arg beyond what we can handle,
951 // or the '>', depending on whether we have too many or too few
952 // arguments.
953 SourceRange Range;
954 if (NumArgs > NumParams)
Douglas Gregor40808ce2009-03-09 23:48:35 +0000955 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
Douglas Gregorc15cb382009-02-09 23:23:08 +0000956 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
957 << (NumArgs > NumParams)
958 << (isa<ClassTemplateDecl>(Template)? 0 :
959 isa<FunctionTemplateDecl>(Template)? 1 :
960 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
961 << Template << Range;
Douglas Gregor62cb18d2009-02-11 18:16:40 +0000962 Diag(Template->getLocation(), diag::note_template_decl_here)
963 << Params->getSourceRange();
Douglas Gregorc15cb382009-02-09 23:23:08 +0000964 Invalid = true;
965 }
966
967 // C++ [temp.arg]p1:
968 // [...] The type and form of each template-argument specified in
969 // a template-id shall match the type and form specified for the
970 // corresponding parameter declared by the template in its
971 // template-parameter-list.
972 unsigned ArgIdx = 0;
973 for (TemplateParameterList::iterator Param = Params->begin(),
974 ParamEnd = Params->end();
975 Param != ParamEnd; ++Param, ++ArgIdx) {
976 // Decode the template argument
Douglas Gregor40808ce2009-03-09 23:48:35 +0000977 TemplateArgument Arg;
Douglas Gregorc15cb382009-02-09 23:23:08 +0000978 if (ArgIdx >= NumArgs) {
Douglas Gregor3e00bad2009-02-17 01:05:43 +0000979 // Retrieve the default template argument from the template
980 // parameter.
981 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
982 if (!TTP->hasDefaultArgument())
983 break;
984
Douglas Gregor40808ce2009-03-09 23:48:35 +0000985 QualType ArgType = TTP->getDefaultArgument();
Douglas Gregor99ebf652009-02-27 19:31:52 +0000986
987 // If the argument type is dependent, instantiate it now based
988 // on the previously-computed template arguments.
Douglas Gregordf667e72009-03-10 20:44:00 +0000989 if (ArgType->isDependentType()) {
990 InstantiatingTemplate Inst(*this, TemplateLoc,
991 Template, &Converted[0],
992 Converted.size(),
993 SourceRange(TemplateLoc, RAngleLoc));
Douglas Gregor99ebf652009-02-27 19:31:52 +0000994 ArgType = InstantiateType(ArgType, &Converted[0], Converted.size(),
995 TTP->getDefaultArgumentLoc(),
996 TTP->getDeclName());
Douglas Gregordf667e72009-03-10 20:44:00 +0000997 }
Douglas Gregor99ebf652009-02-27 19:31:52 +0000998
999 if (ArgType.isNull())
Douglas Gregorcd281c32009-02-28 00:25:32 +00001000 return true;
Douglas Gregor99ebf652009-02-27 19:31:52 +00001001
Douglas Gregor40808ce2009-03-09 23:48:35 +00001002 Arg = TemplateArgument(TTP->getLocation(), ArgType);
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001003 } else if (NonTypeTemplateParmDecl *NTTP
1004 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
1005 if (!NTTP->hasDefaultArgument())
1006 break;
1007
Douglas Gregor2943aed2009-03-03 04:44:36 +00001008 // FIXME: Instantiate default argument
Douglas Gregor40808ce2009-03-09 23:48:35 +00001009 Arg = TemplateArgument(NTTP->getDefaultArgument());
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001010 } else {
1011 TemplateTemplateParmDecl *TempParm
1012 = cast<TemplateTemplateParmDecl>(*Param);
1013
1014 if (!TempParm->hasDefaultArgument())
1015 break;
1016
Douglas Gregor2943aed2009-03-03 04:44:36 +00001017 // FIXME: Instantiate default argument
Douglas Gregor40808ce2009-03-09 23:48:35 +00001018 Arg = TemplateArgument(TempParm->getDefaultArgument());
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001019 }
1020 } else {
1021 // Retrieve the template argument produced by the user.
Douglas Gregor40808ce2009-03-09 23:48:35 +00001022 Arg = TemplateArgs[ArgIdx];
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001023 }
1024
Douglas Gregorc15cb382009-02-09 23:23:08 +00001025
1026 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
1027 // Check template type parameters.
Douglas Gregor40808ce2009-03-09 23:48:35 +00001028 if (Arg.getKind() == TemplateArgument::Type) {
1029 if (CheckTemplateArgument(TTP, Arg.getAsType(), Arg.getLocation()))
Douglas Gregorc15cb382009-02-09 23:23:08 +00001030 Invalid = true;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001031
1032 // Add the converted template type argument.
1033 Converted.push_back(
Douglas Gregor40808ce2009-03-09 23:48:35 +00001034 TemplateArgument(Arg.getLocation(),
1035 Context.getCanonicalType(Arg.getAsType())));
Douglas Gregorc15cb382009-02-09 23:23:08 +00001036 continue;
1037 }
1038
1039 // C++ [temp.arg.type]p1:
1040 // A template-argument for a template-parameter which is a
1041 // type shall be a type-id.
1042
1043 // We have a template type parameter but the template argument
Douglas Gregor40808ce2009-03-09 23:48:35 +00001044 // is not a type.
1045 Diag(Arg.getLocation(), diag::err_template_arg_must_be_type);
Douglas Gregor8b642592009-02-10 00:53:15 +00001046 Diag((*Param)->getLocation(), diag::note_template_param_here);
Douglas Gregorc15cb382009-02-09 23:23:08 +00001047 Invalid = true;
1048 } else if (NonTypeTemplateParmDecl *NTTP
1049 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
1050 // Check non-type template parameters.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001051
1052 // Instantiate the type of the non-type template parameter with
1053 // the template arguments we've seen thus far.
1054 QualType NTTPType = NTTP->getType();
1055 if (NTTPType->isDependentType()) {
1056 // Instantiate the type of the non-type template parameter.
Douglas Gregordf667e72009-03-10 20:44:00 +00001057 InstantiatingTemplate Inst(*this, TemplateLoc,
1058 Template, &Converted[0],
1059 Converted.size(),
1060 SourceRange(TemplateLoc, RAngleLoc));
1061
Douglas Gregor2943aed2009-03-03 04:44:36 +00001062 NTTPType = InstantiateType(NTTPType,
1063 &Converted[0], Converted.size(),
1064 NTTP->getLocation(),
1065 NTTP->getDeclName());
1066 // If that worked, check the non-type template parameter type
1067 // for validity.
1068 if (!NTTPType.isNull())
1069 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
1070 NTTP->getLocation());
1071
1072 if (NTTPType.isNull()) {
1073 Invalid = true;
1074 break;
1075 }
1076 }
1077
Douglas Gregor40808ce2009-03-09 23:48:35 +00001078 switch (Arg.getKind()) {
1079 case TemplateArgument::Expression: {
1080 Expr *E = Arg.getAsExpr();
1081 if (CheckTemplateArgument(NTTP, NTTPType, E, &Converted))
Douglas Gregorc15cb382009-02-09 23:23:08 +00001082 Invalid = true;
Douglas Gregor40808ce2009-03-09 23:48:35 +00001083 break;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001084 }
1085
Douglas Gregor40808ce2009-03-09 23:48:35 +00001086 case TemplateArgument::Declaration:
1087 case TemplateArgument::Integral:
1088 // We've already checked this template argument, so just copy
1089 // it to the list of converted arguments.
1090 Converted.push_back(Arg);
1091 break;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001092
Douglas Gregor40808ce2009-03-09 23:48:35 +00001093 case TemplateArgument::Type:
1094 // We have a non-type template parameter but the template
1095 // argument is a type.
1096
1097 // C++ [temp.arg]p2:
1098 // In a template-argument, an ambiguity between a type-id and
1099 // an expression is resolved to a type-id, regardless of the
1100 // form of the corresponding template-parameter.
1101 //
1102 // We warn specifically about this case, since it can be rather
1103 // confusing for users.
1104 if (Arg.getAsType()->isFunctionType())
1105 Diag(Arg.getLocation(), diag::err_template_arg_nontype_ambig)
1106 << Arg.getAsType();
1107 else
1108 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr);
1109 Diag((*Param)->getLocation(), diag::note_template_param_here);
1110 Invalid = true;
1111 }
Douglas Gregorc15cb382009-02-09 23:23:08 +00001112 } else {
1113 // Check template template parameters.
1114 TemplateTemplateParmDecl *TempParm
1115 = cast<TemplateTemplateParmDecl>(*Param);
1116
Douglas Gregor40808ce2009-03-09 23:48:35 +00001117 switch (Arg.getKind()) {
1118 case TemplateArgument::Expression: {
1119 Expr *ArgExpr = Arg.getAsExpr();
1120 if (ArgExpr && isa<DeclRefExpr>(ArgExpr) &&
1121 isa<TemplateDecl>(cast<DeclRefExpr>(ArgExpr)->getDecl())) {
1122 if (CheckTemplateArgument(TempParm, cast<DeclRefExpr>(ArgExpr)))
1123 Invalid = true;
1124
1125 // Add the converted template argument.
1126 // FIXME: Need the "canonical" template declaration!
1127 Converted.push_back(
1128 TemplateArgument(Arg.getLocation(),
1129 cast<DeclRefExpr>(ArgExpr)->getDecl()));
1130 continue;
1131 }
1132 }
1133 // fall through
1134
1135 case TemplateArgument::Type: {
1136 // We have a template template parameter but the template
1137 // argument does not refer to a template.
1138 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
1139 Invalid = true;
1140 break;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001141 }
1142
Douglas Gregor40808ce2009-03-09 23:48:35 +00001143 case TemplateArgument::Declaration:
1144 // We've already checked this template argument, so just copy
1145 // it to the list of converted arguments.
1146 Converted.push_back(Arg);
1147 break;
1148
1149 case TemplateArgument::Integral:
1150 assert(false && "Integral argument with template template parameter");
1151 break;
1152 }
Douglas Gregorc15cb382009-02-09 23:23:08 +00001153 }
1154 }
1155
1156 return Invalid;
1157}
1158
1159/// \brief Check a template argument against its corresponding
1160/// template type parameter.
1161///
1162/// This routine implements the semantics of C++ [temp.arg.type]. It
1163/// returns true if an error occurred, and false otherwise.
1164bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
1165 QualType Arg, SourceLocation ArgLoc) {
1166 // C++ [temp.arg.type]p2:
1167 // A local type, a type with no linkage, an unnamed type or a type
1168 // compounded from any of these types shall not be used as a
1169 // template-argument for a template type-parameter.
1170 //
1171 // FIXME: Perform the recursive and no-linkage type checks.
1172 const TagType *Tag = 0;
1173 if (const EnumType *EnumT = Arg->getAsEnumType())
1174 Tag = EnumT;
1175 else if (const RecordType *RecordT = Arg->getAsRecordType())
1176 Tag = RecordT;
1177 if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod())
1178 return Diag(ArgLoc, diag::err_template_arg_local_type)
1179 << QualType(Tag, 0);
Douglas Gregor98137532009-03-10 18:33:27 +00001180 else if (Tag && !Tag->getDecl()->getDeclName() &&
1181 !Tag->getDecl()->getTypedefForAnonDecl()) {
Douglas Gregorc15cb382009-02-09 23:23:08 +00001182 Diag(ArgLoc, diag::err_template_arg_unnamed_type);
1183 Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here);
1184 return true;
1185 }
1186
1187 return false;
1188}
1189
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001190/// \brief Checks whether the given template argument is the address
1191/// of an object or function according to C++ [temp.arg.nontype]p1.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001192bool Sema::CheckTemplateArgumentAddressOfObjectOrFunction(Expr *Arg,
1193 NamedDecl *&Entity) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001194 bool Invalid = false;
1195
1196 // See through any implicit casts we added to fix the type.
1197 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
1198 Arg = Cast->getSubExpr();
1199
1200 // C++ [temp.arg.nontype]p1:
1201 //
1202 // A template-argument for a non-type, non-template
1203 // template-parameter shall be one of: [...]
1204 //
1205 // -- the address of an object or function with external
1206 // linkage, including function templates and function
1207 // template-ids but excluding non-static class members,
1208 // expressed as & id-expression where the & is optional if
1209 // the name refers to a function or array, or if the
1210 // corresponding template-parameter is a reference; or
1211 DeclRefExpr *DRE = 0;
1212
1213 // Ignore (and complain about) any excess parentheses.
1214 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
1215 if (!Invalid) {
1216 Diag(Arg->getSourceRange().getBegin(),
1217 diag::err_template_arg_extra_parens)
1218 << Arg->getSourceRange();
1219 Invalid = true;
1220 }
1221
1222 Arg = Parens->getSubExpr();
1223 }
1224
1225 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
1226 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
1227 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
1228 } else
1229 DRE = dyn_cast<DeclRefExpr>(Arg);
1230
1231 if (!DRE || !isa<ValueDecl>(DRE->getDecl()))
1232 return Diag(Arg->getSourceRange().getBegin(),
1233 diag::err_template_arg_not_object_or_func_form)
1234 << Arg->getSourceRange();
1235
1236 // Cannot refer to non-static data members
1237 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl()))
1238 return Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
1239 << Field << Arg->getSourceRange();
1240
1241 // Cannot refer to non-static member functions
1242 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
1243 if (!Method->isStatic())
1244 return Diag(Arg->getSourceRange().getBegin(),
1245 diag::err_template_arg_method)
1246 << Method << Arg->getSourceRange();
1247
1248 // Functions must have external linkage.
1249 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
1250 if (Func->getStorageClass() == FunctionDecl::Static) {
1251 Diag(Arg->getSourceRange().getBegin(),
1252 diag::err_template_arg_function_not_extern)
1253 << Func << Arg->getSourceRange();
1254 Diag(Func->getLocation(), diag::note_template_arg_internal_object)
1255 << true;
1256 return true;
1257 }
1258
1259 // Okay: we've named a function with external linkage.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001260 Entity = Func;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001261 return Invalid;
1262 }
1263
1264 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
1265 if (!Var->hasGlobalStorage()) {
1266 Diag(Arg->getSourceRange().getBegin(),
1267 diag::err_template_arg_object_not_extern)
1268 << Var << Arg->getSourceRange();
1269 Diag(Var->getLocation(), diag::note_template_arg_internal_object)
1270 << true;
1271 return true;
1272 }
1273
1274 // Okay: we've named an object with external linkage
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001275 Entity = Var;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001276 return Invalid;
1277 }
1278
1279 // We found something else, but we don't know specifically what it is.
1280 Diag(Arg->getSourceRange().getBegin(),
1281 diag::err_template_arg_not_object_or_func)
1282 << Arg->getSourceRange();
1283 Diag(DRE->getDecl()->getLocation(),
1284 diag::note_template_arg_refers_here);
1285 return true;
1286}
1287
1288/// \brief Checks whether the given template argument is a pointer to
1289/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001290bool
1291Sema::CheckTemplateArgumentPointerToMember(Expr *Arg, NamedDecl *&Member) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001292 bool Invalid = false;
1293
1294 // See through any implicit casts we added to fix the type.
1295 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
1296 Arg = Cast->getSubExpr();
1297
1298 // C++ [temp.arg.nontype]p1:
1299 //
1300 // A template-argument for a non-type, non-template
1301 // template-parameter shall be one of: [...]
1302 //
1303 // -- a pointer to member expressed as described in 5.3.1.
1304 QualifiedDeclRefExpr *DRE = 0;
1305
1306 // Ignore (and complain about) any excess parentheses.
1307 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
1308 if (!Invalid) {
1309 Diag(Arg->getSourceRange().getBegin(),
1310 diag::err_template_arg_extra_parens)
1311 << Arg->getSourceRange();
1312 Invalid = true;
1313 }
1314
1315 Arg = Parens->getSubExpr();
1316 }
1317
1318 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg))
1319 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
1320 DRE = dyn_cast<QualifiedDeclRefExpr>(UnOp->getSubExpr());
1321
1322 if (!DRE)
1323 return Diag(Arg->getSourceRange().getBegin(),
1324 diag::err_template_arg_not_pointer_to_member_form)
1325 << Arg->getSourceRange();
1326
1327 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
1328 assert((isa<FieldDecl>(DRE->getDecl()) ||
1329 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
1330 "Only non-static member pointers can make it here");
1331
1332 // Okay: this is the address of a non-static member, and therefore
1333 // a member pointer constant.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001334 Member = DRE->getDecl();
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001335 return Invalid;
1336 }
1337
1338 // We found something else, but we don't know specifically what it is.
1339 Diag(Arg->getSourceRange().getBegin(),
1340 diag::err_template_arg_not_pointer_to_member_form)
1341 << Arg->getSourceRange();
1342 Diag(DRE->getDecl()->getLocation(),
1343 diag::note_template_arg_refers_here);
1344 return true;
1345}
1346
Douglas Gregorc15cb382009-02-09 23:23:08 +00001347/// \brief Check a template argument against its corresponding
1348/// non-type template parameter.
1349///
Douglas Gregor2943aed2009-03-03 04:44:36 +00001350/// This routine implements the semantics of C++ [temp.arg.nontype].
1351/// It returns true if an error occurred, and false otherwise. \p
1352/// InstantiatedParamType is the type of the non-type template
1353/// parameter after it has been instantiated.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001354///
1355/// If Converted is non-NULL and no errors occur, the value
1356/// of this argument will be added to the end of the Converted vector.
Douglas Gregorc15cb382009-02-09 23:23:08 +00001357bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Douglas Gregor2943aed2009-03-03 04:44:36 +00001358 QualType InstantiatedParamType, Expr *&Arg,
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001359 llvm::SmallVectorImpl<TemplateArgument> *Converted) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00001360 SourceLocation StartLoc = Arg->getSourceRange().getBegin();
1361
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001362 // If either the parameter has a dependent type or the argument is
1363 // type-dependent, there's nothing we can check now.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001364 // FIXME: Add template argument to Converted!
Douglas Gregor40808ce2009-03-09 23:48:35 +00001365 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
1366 // FIXME: Produce a cloned, canonical expression?
1367 Converted->push_back(TemplateArgument(Arg));
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001368 return false;
Douglas Gregor40808ce2009-03-09 23:48:35 +00001369 }
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001370
1371 // C++ [temp.arg.nontype]p5:
1372 // The following conversions are performed on each expression used
1373 // as a non-type template-argument. If a non-type
1374 // template-argument cannot be converted to the type of the
1375 // corresponding template-parameter then the program is
1376 // ill-formed.
1377 //
1378 // -- for a non-type template-parameter of integral or
1379 // enumeration type, integral promotions (4.5) and integral
1380 // conversions (4.7) are applied.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001381 QualType ParamType = InstantiatedParamType;
Douglas Gregora35284b2009-02-11 00:19:33 +00001382 QualType ArgType = Arg->getType();
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001383 if (ParamType->isIntegralType() || ParamType->isEnumeralType()) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001384 // C++ [temp.arg.nontype]p1:
1385 // A template-argument for a non-type, non-template
1386 // template-parameter shall be one of:
1387 //
1388 // -- an integral constant-expression of integral or enumeration
1389 // type; or
1390 // -- the name of a non-type template-parameter; or
1391 SourceLocation NonConstantLoc;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001392 llvm::APSInt Value;
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001393 if (!ArgType->isIntegralType() && !ArgType->isEnumeralType()) {
1394 Diag(Arg->getSourceRange().getBegin(),
1395 diag::err_template_arg_not_integral_or_enumeral)
1396 << ArgType << Arg->getSourceRange();
1397 Diag(Param->getLocation(), diag::note_template_param_here);
1398 return true;
1399 } else if (!Arg->isValueDependent() &&
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001400 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001401 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
1402 << ArgType << Arg->getSourceRange();
1403 return true;
1404 }
1405
1406 // FIXME: We need some way to more easily get the unqualified form
1407 // of the types without going all the way to the
1408 // canonical type.
1409 if (Context.getCanonicalType(ParamType).getCVRQualifiers())
1410 ParamType = Context.getCanonicalType(ParamType).getUnqualifiedType();
1411 if (Context.getCanonicalType(ArgType).getCVRQualifiers())
1412 ArgType = Context.getCanonicalType(ArgType).getUnqualifiedType();
1413
1414 // Try to convert the argument to the parameter's type.
1415 if (ParamType == ArgType) {
1416 // Okay: no conversion necessary
1417 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
1418 !ParamType->isEnumeralType()) {
1419 // This is an integral promotion or conversion.
1420 ImpCastExprToType(Arg, ParamType);
1421 } else {
1422 // We can't perform this conversion.
1423 Diag(Arg->getSourceRange().getBegin(),
1424 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00001425 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001426 Diag(Param->getLocation(), diag::note_template_param_here);
1427 return true;
1428 }
1429
Douglas Gregorf80a9d52009-03-14 00:20:21 +00001430 QualType IntegerType = Context.getCanonicalType(ParamType);
1431 if (const EnumType *Enum = IntegerType->getAsEnumType())
1432 IntegerType = Enum->getDecl()->getIntegerType();
1433
1434 if (!Arg->isValueDependent()) {
1435 // Check that an unsigned parameter does not receive a negative
1436 // value.
1437 if (IntegerType->isUnsignedIntegerType()
1438 && (Value.isSigned() && Value.isNegative())) {
1439 Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_negative)
1440 << Value.toString(10) << Param->getType()
1441 << Arg->getSourceRange();
1442 Diag(Param->getLocation(), diag::note_template_param_here);
1443 return true;
1444 }
1445
1446 // Check that we don't overflow the template parameter type.
1447 unsigned AllowedBits = Context.getTypeSize(IntegerType);
1448 if (Value.getActiveBits() > AllowedBits) {
1449 Diag(Arg->getSourceRange().getBegin(),
1450 diag::err_template_arg_too_large)
1451 << Value.toString(10) << Param->getType()
1452 << Arg->getSourceRange();
1453 Diag(Param->getLocation(), diag::note_template_param_here);
1454 return true;
1455 }
1456
1457 if (Value.getBitWidth() != AllowedBits)
1458 Value.extOrTrunc(AllowedBits);
1459 Value.setIsSigned(IntegerType->isSignedIntegerType());
1460 }
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001461
1462 if (Converted) {
1463 // Add the value of this argument to the list of converted
1464 // arguments. We use the bitwidth and signedness of the template
1465 // parameter.
Douglas Gregorba498172009-03-13 21:01:28 +00001466 if (Arg->isValueDependent()) {
1467 // The argument is value-dependent. Create a new
1468 // TemplateArgument with the converted expression.
1469 Converted->push_back(TemplateArgument(Arg));
1470 return false;
1471 }
1472
Douglas Gregor5b0f7522009-03-14 00:03:48 +00001473 Converted->push_back(TemplateArgument(StartLoc, Value,
Douglas Gregorc971f862009-03-12 22:20:26 +00001474 Context.getCanonicalType(IntegerType)));
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001475 }
1476
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001477 return false;
1478 }
Douglas Gregora35284b2009-02-11 00:19:33 +00001479
Douglas Gregorb86b0572009-02-11 01:18:59 +00001480 // Handle pointer-to-function, reference-to-function, and
1481 // pointer-to-member-function all in (roughly) the same way.
1482 if (// -- For a non-type template-parameter of type pointer to
1483 // function, only the function-to-pointer conversion (4.3) is
1484 // applied. If the template-argument represents a set of
1485 // overloaded functions (or a pointer to such), the matching
1486 // function is selected from the set (13.4).
1487 (ParamType->isPointerType() &&
1488 ParamType->getAsPointerType()->getPointeeType()->isFunctionType()) ||
1489 // -- For a non-type template-parameter of type reference to
1490 // function, no conversions apply. If the template-argument
1491 // represents a set of overloaded functions, the matching
1492 // function is selected from the set (13.4).
1493 (ParamType->isReferenceType() &&
1494 ParamType->getAsReferenceType()->getPointeeType()->isFunctionType()) ||
1495 // -- For a non-type template-parameter of type pointer to
1496 // member function, no conversions apply. If the
1497 // template-argument represents a set of overloaded member
1498 // functions, the matching member function is selected from
1499 // the set (13.4).
1500 (ParamType->isMemberPointerType() &&
1501 ParamType->getAsMemberPointerType()->getPointeeType()
1502 ->isFunctionType())) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001503 if (Context.hasSameUnqualifiedType(ArgType,
1504 ParamType.getNonReferenceType())) {
Douglas Gregora35284b2009-02-11 00:19:33 +00001505 // We don't have to do anything: the types already match.
Douglas Gregorb86b0572009-02-11 01:18:59 +00001506 } else if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregora35284b2009-02-11 00:19:33 +00001507 ArgType = Context.getPointerType(ArgType);
1508 ImpCastExprToType(Arg, ArgType);
1509 } else if (FunctionDecl *Fn
1510 = ResolveAddressOfOverloadedFunction(Arg, ParamType, true)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001511 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
1512 return true;
1513
Douglas Gregora35284b2009-02-11 00:19:33 +00001514 FixOverloadedFunctionReference(Arg, Fn);
1515 ArgType = Arg->getType();
Douglas Gregorb86b0572009-02-11 01:18:59 +00001516 if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregora35284b2009-02-11 00:19:33 +00001517 ArgType = Context.getPointerType(Arg->getType());
1518 ImpCastExprToType(Arg, ArgType);
1519 }
1520 }
1521
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001522 if (!Context.hasSameUnqualifiedType(ArgType,
1523 ParamType.getNonReferenceType())) {
Douglas Gregora35284b2009-02-11 00:19:33 +00001524 // We can't perform this conversion.
1525 Diag(Arg->getSourceRange().getBegin(),
1526 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00001527 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregora35284b2009-02-11 00:19:33 +00001528 Diag(Param->getLocation(), diag::note_template_param_here);
1529 return true;
1530 }
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001531
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001532 if (ParamType->isMemberPointerType()) {
1533 NamedDecl *Member = 0;
1534 if (CheckTemplateArgumentPointerToMember(Arg, Member))
1535 return true;
1536
1537 if (Converted)
Douglas Gregor40808ce2009-03-09 23:48:35 +00001538 Converted->push_back(TemplateArgument(StartLoc, Member));
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001539
1540 return false;
1541 }
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001542
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001543 NamedDecl *Entity = 0;
1544 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1545 return true;
1546
1547 if (Converted)
Douglas Gregor40808ce2009-03-09 23:48:35 +00001548 Converted->push_back(TemplateArgument(StartLoc, Entity));
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001549 return false;
Douglas Gregora35284b2009-02-11 00:19:33 +00001550 }
1551
Chris Lattnerfe90de72009-02-20 21:37:53 +00001552 if (ParamType->isPointerType()) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00001553 // -- for a non-type template-parameter of type pointer to
1554 // object, qualification conversions (4.4) and the
1555 // array-to-pointer conversion (4.2) are applied.
Douglas Gregorbad0e652009-03-24 20:32:41 +00001556 assert(ParamType->getAsPointerType()->getPointeeType()->isObjectType() &&
Douglas Gregorb86b0572009-02-11 01:18:59 +00001557 "Only object pointers allowed here");
Douglas Gregorf684e6e2009-02-11 00:44:29 +00001558
Douglas Gregorb86b0572009-02-11 01:18:59 +00001559 if (ArgType->isArrayType()) {
1560 ArgType = Context.getArrayDecayedType(ArgType);
1561 ImpCastExprToType(Arg, ArgType);
Douglas Gregorf684e6e2009-02-11 00:44:29 +00001562 }
Douglas Gregorb86b0572009-02-11 01:18:59 +00001563
1564 if (IsQualificationConversion(ArgType, ParamType)) {
1565 ArgType = ParamType;
1566 ImpCastExprToType(Arg, ParamType);
1567 }
1568
Douglas Gregor8e6563b2009-02-11 18:22:40 +00001569 if (!Context.hasSameUnqualifiedType(ArgType, ParamType)) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00001570 // We can't perform this conversion.
1571 Diag(Arg->getSourceRange().getBegin(),
1572 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00001573 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregorb86b0572009-02-11 01:18:59 +00001574 Diag(Param->getLocation(), diag::note_template_param_here);
1575 return true;
1576 }
1577
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001578 NamedDecl *Entity = 0;
1579 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1580 return true;
1581
1582 if (Converted)
Douglas Gregor40808ce2009-03-09 23:48:35 +00001583 Converted->push_back(TemplateArgument(StartLoc, Entity));
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001584
1585 return false;
Douglas Gregorf684e6e2009-02-11 00:44:29 +00001586 }
Douglas Gregorb86b0572009-02-11 01:18:59 +00001587
1588 if (const ReferenceType *ParamRefType = ParamType->getAsReferenceType()) {
1589 // -- For a non-type template-parameter of type reference to
1590 // object, no conversions apply. The type referred to by the
1591 // reference may be more cv-qualified than the (otherwise
1592 // identical) type of the template-argument. The
1593 // template-parameter is bound directly to the
1594 // template-argument, which must be an lvalue.
Douglas Gregorbad0e652009-03-24 20:32:41 +00001595 assert(ParamRefType->getPointeeType()->isObjectType() &&
Douglas Gregorb86b0572009-02-11 01:18:59 +00001596 "Only object references allowed here");
Douglas Gregorf684e6e2009-02-11 00:44:29 +00001597
Douglas Gregor8e6563b2009-02-11 18:22:40 +00001598 if (!Context.hasSameUnqualifiedType(ParamRefType->getPointeeType(), ArgType)) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00001599 Diag(Arg->getSourceRange().getBegin(),
1600 diag::err_template_arg_no_ref_bind)
Douglas Gregor2943aed2009-03-03 04:44:36 +00001601 << InstantiatedParamType << Arg->getType()
Douglas Gregorb86b0572009-02-11 01:18:59 +00001602 << Arg->getSourceRange();
1603 Diag(Param->getLocation(), diag::note_template_param_here);
1604 return true;
1605 }
1606
1607 unsigned ParamQuals
1608 = Context.getCanonicalType(ParamType).getCVRQualifiers();
1609 unsigned ArgQuals = Context.getCanonicalType(ArgType).getCVRQualifiers();
1610
1611 if ((ParamQuals | ArgQuals) != ParamQuals) {
1612 Diag(Arg->getSourceRange().getBegin(),
1613 diag::err_template_arg_ref_bind_ignores_quals)
Douglas Gregor2943aed2009-03-03 04:44:36 +00001614 << InstantiatedParamType << Arg->getType()
Douglas Gregorb86b0572009-02-11 01:18:59 +00001615 << Arg->getSourceRange();
1616 Diag(Param->getLocation(), diag::note_template_param_here);
1617 return true;
1618 }
1619
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001620 NamedDecl *Entity = 0;
1621 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1622 return true;
1623
1624 if (Converted)
Douglas Gregor40808ce2009-03-09 23:48:35 +00001625 Converted->push_back(TemplateArgument(StartLoc, Entity));
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001626
1627 return false;
Douglas Gregorb86b0572009-02-11 01:18:59 +00001628 }
Douglas Gregor658bbb52009-02-11 16:16:59 +00001629
1630 // -- For a non-type template-parameter of type pointer to data
1631 // member, qualification conversions (4.4) are applied.
1632 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
1633
Douglas Gregor8e6563b2009-02-11 18:22:40 +00001634 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
Douglas Gregor658bbb52009-02-11 16:16:59 +00001635 // Types match exactly: nothing more to do here.
1636 } else if (IsQualificationConversion(ArgType, ParamType)) {
1637 ImpCastExprToType(Arg, ParamType);
1638 } else {
1639 // We can't perform this conversion.
1640 Diag(Arg->getSourceRange().getBegin(),
1641 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00001642 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor658bbb52009-02-11 16:16:59 +00001643 Diag(Param->getLocation(), diag::note_template_param_here);
1644 return true;
1645 }
1646
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001647 NamedDecl *Member = 0;
1648 if (CheckTemplateArgumentPointerToMember(Arg, Member))
1649 return true;
1650
1651 if (Converted)
Douglas Gregor40808ce2009-03-09 23:48:35 +00001652 Converted->push_back(TemplateArgument(StartLoc, Member));
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001653
1654 return false;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001655}
1656
1657/// \brief Check a template argument against its corresponding
1658/// template template parameter.
1659///
1660/// This routine implements the semantics of C++ [temp.arg.template].
1661/// It returns true if an error occurred, and false otherwise.
1662bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
1663 DeclRefExpr *Arg) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00001664 assert(isa<TemplateDecl>(Arg->getDecl()) && "Only template decls allowed");
1665 TemplateDecl *Template = cast<TemplateDecl>(Arg->getDecl());
1666
1667 // C++ [temp.arg.template]p1:
1668 // A template-argument for a template template-parameter shall be
1669 // the name of a class template, expressed as id-expression. Only
1670 // primary class templates are considered when matching the
1671 // template template argument with the corresponding parameter;
1672 // partial specializations are not considered even if their
1673 // parameter lists match that of the template template parameter.
1674 if (!isa<ClassTemplateDecl>(Template)) {
1675 assert(isa<FunctionTemplateDecl>(Template) &&
1676 "Only function templates are possible here");
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001677 Diag(Arg->getSourceRange().getBegin(),
1678 diag::note_template_arg_refers_here_func)
Douglas Gregordd0574e2009-02-10 00:24:35 +00001679 << Template;
1680 }
1681
1682 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
1683 Param->getTemplateParameters(),
1684 true, true,
1685 Arg->getSourceRange().getBegin());
Douglas Gregorc15cb382009-02-09 23:23:08 +00001686}
1687
Douglas Gregorddc29e12009-02-06 22:42:48 +00001688/// \brief Determine whether the given template parameter lists are
1689/// equivalent.
1690///
1691/// \param New The new template parameter list, typically written in the
1692/// source code as part of a new template declaration.
1693///
1694/// \param Old The old template parameter list, typically found via
1695/// name lookup of the template declared with this template parameter
1696/// list.
1697///
1698/// \param Complain If true, this routine will produce a diagnostic if
1699/// the template parameter lists are not equivalent.
1700///
Douglas Gregordd0574e2009-02-10 00:24:35 +00001701/// \param IsTemplateTemplateParm If true, this routine is being
1702/// called to compare the template parameter lists of a template
1703/// template parameter.
1704///
1705/// \param TemplateArgLoc If this source location is valid, then we
1706/// are actually checking the template parameter list of a template
1707/// argument (New) against the template parameter list of its
1708/// corresponding template template parameter (Old). We produce
1709/// slightly different diagnostics in this scenario.
1710///
Douglas Gregorddc29e12009-02-06 22:42:48 +00001711/// \returns True if the template parameter lists are equal, false
1712/// otherwise.
1713bool
1714Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
1715 TemplateParameterList *Old,
1716 bool Complain,
Douglas Gregordd0574e2009-02-10 00:24:35 +00001717 bool IsTemplateTemplateParm,
1718 SourceLocation TemplateArgLoc) {
Douglas Gregorddc29e12009-02-06 22:42:48 +00001719 if (Old->size() != New->size()) {
1720 if (Complain) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00001721 unsigned NextDiag = diag::err_template_param_list_different_arity;
1722 if (TemplateArgLoc.isValid()) {
1723 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
1724 NextDiag = diag::note_template_param_list_different_arity;
1725 }
1726 Diag(New->getTemplateLoc(), NextDiag)
1727 << (New->size() > Old->size())
1728 << IsTemplateTemplateParm
1729 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
Douglas Gregorddc29e12009-02-06 22:42:48 +00001730 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
1731 << IsTemplateTemplateParm
1732 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
1733 }
1734
1735 return false;
1736 }
1737
1738 for (TemplateParameterList::iterator OldParm = Old->begin(),
1739 OldParmEnd = Old->end(), NewParm = New->begin();
1740 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
1741 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00001742 unsigned NextDiag = diag::err_template_param_different_kind;
1743 if (TemplateArgLoc.isValid()) {
1744 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
1745 NextDiag = diag::note_template_param_different_kind;
1746 }
1747 Diag((*NewParm)->getLocation(), NextDiag)
Douglas Gregorddc29e12009-02-06 22:42:48 +00001748 << IsTemplateTemplateParm;
1749 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
1750 << IsTemplateTemplateParm;
1751 return false;
1752 }
1753
1754 if (isa<TemplateTypeParmDecl>(*OldParm)) {
1755 // Okay; all template type parameters are equivalent (since we
Douglas Gregordd0574e2009-02-10 00:24:35 +00001756 // know we're at the same index).
1757#if 0
1758 // FIXME: Enable this code in debug mode *after* we properly go
1759 // through and "instantiate" the template parameter lists of
1760 // template template parameters. It's only after this
1761 // instantiation that (1) any dependent types within the
1762 // template parameter list of the template template parameter
1763 // can be checked, and (2) the template type parameter depths
1764 // will match up.
Douglas Gregorddc29e12009-02-06 22:42:48 +00001765 QualType OldParmType
1766 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*OldParm));
1767 QualType NewParmType
1768 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*NewParm));
1769 assert(Context.getCanonicalType(OldParmType) ==
1770 Context.getCanonicalType(NewParmType) &&
1771 "type parameter mismatch?");
1772#endif
1773 } else if (NonTypeTemplateParmDecl *OldNTTP
1774 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
1775 // The types of non-type template parameters must agree.
1776 NonTypeTemplateParmDecl *NewNTTP
1777 = cast<NonTypeTemplateParmDecl>(*NewParm);
1778 if (Context.getCanonicalType(OldNTTP->getType()) !=
1779 Context.getCanonicalType(NewNTTP->getType())) {
1780 if (Complain) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00001781 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
1782 if (TemplateArgLoc.isValid()) {
1783 Diag(TemplateArgLoc,
1784 diag::err_template_arg_template_params_mismatch);
1785 NextDiag = diag::note_template_nontype_parm_different_type;
1786 }
1787 Diag(NewNTTP->getLocation(), NextDiag)
Douglas Gregorddc29e12009-02-06 22:42:48 +00001788 << NewNTTP->getType()
1789 << IsTemplateTemplateParm;
1790 Diag(OldNTTP->getLocation(),
1791 diag::note_template_nontype_parm_prev_declaration)
1792 << OldNTTP->getType();
1793 }
1794 return false;
1795 }
1796 } else {
1797 // The template parameter lists of template template
1798 // parameters must agree.
1799 // FIXME: Could we perform a faster "type" comparison here?
1800 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
1801 "Only template template parameters handled here");
1802 TemplateTemplateParmDecl *OldTTP
1803 = cast<TemplateTemplateParmDecl>(*OldParm);
1804 TemplateTemplateParmDecl *NewTTP
1805 = cast<TemplateTemplateParmDecl>(*NewParm);
1806 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
1807 OldTTP->getTemplateParameters(),
1808 Complain,
Douglas Gregordd0574e2009-02-10 00:24:35 +00001809 /*IsTemplateTemplateParm=*/true,
1810 TemplateArgLoc))
Douglas Gregorddc29e12009-02-06 22:42:48 +00001811 return false;
1812 }
1813 }
1814
1815 return true;
1816}
1817
1818/// \brief Check whether a template can be declared within this scope.
1819///
1820/// If the template declaration is valid in this scope, returns
1821/// false. Otherwise, issues a diagnostic and returns true.
1822bool
1823Sema::CheckTemplateDeclScope(Scope *S,
1824 MultiTemplateParamsArg &TemplateParameterLists) {
1825 assert(TemplateParameterLists.size() > 0 && "Not a template");
1826
1827 // Find the nearest enclosing declaration scope.
1828 while ((S->getFlags() & Scope::DeclScope) == 0 ||
1829 (S->getFlags() & Scope::TemplateParamScope) != 0)
1830 S = S->getParent();
1831
1832 TemplateParameterList *TemplateParams =
1833 static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
1834 SourceLocation TemplateLoc = TemplateParams->getTemplateLoc();
1835 SourceRange TemplateRange
1836 = SourceRange(TemplateLoc, TemplateParams->getRAngleLoc());
1837
1838 // C++ [temp]p2:
1839 // A template-declaration can appear only as a namespace scope or
1840 // class scope declaration.
1841 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
1842 while (Ctx && isa<LinkageSpecDecl>(Ctx)) {
1843 if (cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
1844 return Diag(TemplateLoc, diag::err_template_linkage)
1845 << TemplateRange;
1846
1847 Ctx = Ctx->getParent();
1848 }
1849
1850 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
1851 return false;
1852
1853 return Diag(TemplateLoc, diag::err_template_outside_namespace_or_class_scope)
1854 << TemplateRange;
1855}
Douglas Gregorcc636682009-02-17 23:15:12 +00001856
Douglas Gregor88b70942009-02-25 22:02:03 +00001857/// \brief Check whether a class template specialization in the
1858/// current context is well-formed.
1859///
1860/// This routine determines whether a class template specialization
1861/// can be declared in the current context (C++ [temp.expl.spec]p2)
1862/// and emits appropriate diagnostics if there was an error. It
1863/// returns true if there was an error that we cannot recover from,
1864/// and false otherwise.
1865bool
1866Sema::CheckClassTemplateSpecializationScope(ClassTemplateDecl *ClassTemplate,
1867 ClassTemplateSpecializationDecl *PrevDecl,
1868 SourceLocation TemplateNameLoc,
1869 SourceRange ScopeSpecifierRange) {
1870 // C++ [temp.expl.spec]p2:
1871 // An explicit specialization shall be declared in the namespace
1872 // of which the template is a member, or, for member templates, in
1873 // the namespace of which the enclosing class or enclosing class
1874 // template is a member. An explicit specialization of a member
1875 // function, member class or static data member of a class
1876 // template shall be declared in the namespace of which the class
1877 // template is a member. Such a declaration may also be a
1878 // definition. If the declaration is not a definition, the
1879 // specialization may be defined later in the name- space in which
1880 // the explicit specialization was declared, or in a namespace
1881 // that encloses the one in which the explicit specialization was
1882 // declared.
1883 if (CurContext->getLookupContext()->isFunctionOrMethod()) {
1884 Diag(TemplateNameLoc, diag::err_template_spec_decl_function_scope)
1885 << ClassTemplate;
1886 return true;
1887 }
1888
1889 DeclContext *DC = CurContext->getEnclosingNamespaceContext();
1890 DeclContext *TemplateContext
1891 = ClassTemplate->getDeclContext()->getEnclosingNamespaceContext();
1892 if (!PrevDecl || PrevDecl->getSpecializationKind() == TSK_Undeclared) {
1893 // There is no prior declaration of this entity, so this
1894 // specialization must be in the same context as the template
1895 // itself.
1896 if (DC != TemplateContext) {
1897 if (isa<TranslationUnitDecl>(TemplateContext))
1898 Diag(TemplateNameLoc, diag::err_template_spec_decl_out_of_scope_global)
1899 << ClassTemplate << ScopeSpecifierRange;
1900 else if (isa<NamespaceDecl>(TemplateContext))
1901 Diag(TemplateNameLoc, diag::err_template_spec_decl_out_of_scope)
1902 << ClassTemplate << cast<NamedDecl>(TemplateContext)
1903 << ScopeSpecifierRange;
1904
1905 Diag(ClassTemplate->getLocation(), diag::note_template_decl_here);
1906 }
1907
1908 return false;
1909 }
1910
1911 // We have a previous declaration of this entity. Make sure that
1912 // this redeclaration (or definition) occurs in an enclosing namespace.
1913 if (!CurContext->Encloses(TemplateContext)) {
1914 if (isa<TranslationUnitDecl>(TemplateContext))
1915 Diag(TemplateNameLoc, diag::err_template_spec_redecl_global_scope)
1916 << ClassTemplate << ScopeSpecifierRange;
1917 else if (isa<NamespaceDecl>(TemplateContext))
1918 Diag(TemplateNameLoc, diag::err_template_spec_redecl_out_of_scope)
1919 << ClassTemplate << cast<NamedDecl>(TemplateContext)
1920 << ScopeSpecifierRange;
1921
1922 Diag(ClassTemplate->getLocation(), diag::note_template_decl_here);
1923 }
1924
1925 return false;
1926}
1927
Douglas Gregor212e81c2009-03-25 00:13:59 +00001928Sema::DeclResult
Douglas Gregorcc636682009-02-17 23:15:12 +00001929Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec, TagKind TK,
1930 SourceLocation KWLoc,
1931 const CXXScopeSpec &SS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00001932 TemplateTy TemplateD,
Douglas Gregorcc636682009-02-17 23:15:12 +00001933 SourceLocation TemplateNameLoc,
1934 SourceLocation LAngleLoc,
Douglas Gregor40808ce2009-03-09 23:48:35 +00001935 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregorcc636682009-02-17 23:15:12 +00001936 SourceLocation *TemplateArgLocs,
1937 SourceLocation RAngleLoc,
1938 AttributeList *Attr,
1939 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregorcc636682009-02-17 23:15:12 +00001940 // Find the class template we're specializing
Douglas Gregor7532dc62009-03-30 22:58:21 +00001941 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Douglas Gregorcc636682009-02-17 23:15:12 +00001942 ClassTemplateDecl *ClassTemplate
Douglas Gregor7532dc62009-03-30 22:58:21 +00001943 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
Douglas Gregorcc636682009-02-17 23:15:12 +00001944
Douglas Gregor88b70942009-02-25 22:02:03 +00001945 // Check the validity of the template headers that introduce this
1946 // template.
Douglas Gregor6bc9f7e2009-02-25 22:18:32 +00001947 // FIXME: Once we have member templates, we'll need to check
1948 // C++ [temp.expl.spec]p17-18, where we could have multiple levels of
1949 // template<> headers.
Douglas Gregor4b2d3f72009-02-26 21:00:50 +00001950 if (TemplateParameterLists.size() == 0)
1951 Diag(KWLoc, diag::err_template_spec_needs_header)
Douglas Gregorb2fb6de2009-02-27 17:53:17 +00001952 << CodeModificationHint::CreateInsertion(KWLoc, "template<> ");
Douglas Gregor4b2d3f72009-02-26 21:00:50 +00001953 else {
Douglas Gregor88b70942009-02-25 22:02:03 +00001954 TemplateParameterList *TemplateParams
1955 = static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
Chris Lattnerb28317a2009-03-28 19:18:32 +00001956 if (TemplateParameterLists.size() > 1) {
1957 Diag(TemplateParams->getTemplateLoc(),
1958 diag::err_template_spec_extra_headers);
1959 return true;
1960 }
Douglas Gregor88b70942009-02-25 22:02:03 +00001961
Chris Lattnerb28317a2009-03-28 19:18:32 +00001962 if (TemplateParams->size() > 0) {
Douglas Gregor88b70942009-02-25 22:02:03 +00001963 // FIXME: No support for class template partial specialization.
Chris Lattnerb28317a2009-03-28 19:18:32 +00001964 Diag(TemplateParams->getTemplateLoc(), diag::unsup_template_partial_spec);
1965 return true;
1966 }
Douglas Gregor88b70942009-02-25 22:02:03 +00001967 }
1968
Douglas Gregorcc636682009-02-17 23:15:12 +00001969 // Check that the specialization uses the same tag kind as the
1970 // original template.
1971 TagDecl::TagKind Kind;
1972 switch (TagSpec) {
1973 default: assert(0 && "Unknown tag type!");
1974 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
1975 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
1976 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
1977 }
1978 if (ClassTemplate->getTemplatedDecl()->getTagKind() != Kind) {
Douglas Gregora3a83512009-04-01 23:51:29 +00001979 Diag(KWLoc, diag::err_use_with_wrong_tag)
1980 << ClassTemplate
1981 << CodeModificationHint::CreateReplacement(KWLoc,
1982 ClassTemplate->getTemplatedDecl()->getKindName());
Douglas Gregorcc636682009-02-17 23:15:12 +00001983 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
1984 diag::note_previous_use);
1985 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
1986 }
1987
Douglas Gregor40808ce2009-03-09 23:48:35 +00001988 // Translate the parser's template argument list in our AST format.
1989 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
1990 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
1991
Douglas Gregorcc636682009-02-17 23:15:12 +00001992 // Check that the template argument list is well-formed for this
1993 // template.
1994 llvm::SmallVector<TemplateArgument, 16> ConvertedTemplateArgs;
1995 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
Douglas Gregor40808ce2009-03-09 23:48:35 +00001996 &TemplateArgs[0], TemplateArgs.size(),
1997 RAngleLoc, ConvertedTemplateArgs))
Douglas Gregor212e81c2009-03-25 00:13:59 +00001998 return true;
Douglas Gregorcc636682009-02-17 23:15:12 +00001999
2000 assert((ConvertedTemplateArgs.size() ==
2001 ClassTemplate->getTemplateParameters()->size()) &&
2002 "Converted template argument list is too short!");
2003
2004 // Find the class template specialization declaration that
2005 // corresponds to these arguments.
2006 llvm::FoldingSetNodeID ID;
2007 ClassTemplateSpecializationDecl::Profile(ID, &ConvertedTemplateArgs[0],
2008 ConvertedTemplateArgs.size());
2009 void *InsertPos = 0;
2010 ClassTemplateSpecializationDecl *PrevDecl
2011 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
2012
2013 ClassTemplateSpecializationDecl *Specialization = 0;
2014
Douglas Gregor88b70942009-02-25 22:02:03 +00002015 // Check whether we can declare a class template specialization in
2016 // the current scope.
2017 if (CheckClassTemplateSpecializationScope(ClassTemplate, PrevDecl,
2018 TemplateNameLoc,
2019 SS.getRange()))
Douglas Gregor212e81c2009-03-25 00:13:59 +00002020 return true;
Douglas Gregor88b70942009-02-25 22:02:03 +00002021
Douglas Gregorcc636682009-02-17 23:15:12 +00002022 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
2023 // Since the only prior class template specialization with these
2024 // arguments was referenced but not declared, reuse that
2025 // declaration node as our own, updating its source location to
2026 // reflect our new declaration.
Douglas Gregorcc636682009-02-17 23:15:12 +00002027 Specialization = PrevDecl;
Douglas Gregor6bc9f7e2009-02-25 22:18:32 +00002028 Specialization->setLocation(TemplateNameLoc);
Douglas Gregorcc636682009-02-17 23:15:12 +00002029 PrevDecl = 0;
2030 } else {
2031 // Create a new class template specialization declaration node for
2032 // this explicit specialization.
2033 Specialization
2034 = ClassTemplateSpecializationDecl::Create(Context,
2035 ClassTemplate->getDeclContext(),
2036 TemplateNameLoc,
2037 ClassTemplate,
2038 &ConvertedTemplateArgs[0],
2039 ConvertedTemplateArgs.size(),
2040 PrevDecl);
2041
2042 if (PrevDecl) {
2043 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
2044 ClassTemplate->getSpecializations().GetOrInsertNode(Specialization);
2045 } else {
2046 ClassTemplate->getSpecializations().InsertNode(Specialization,
2047 InsertPos);
2048 }
2049 }
2050
2051 // Note that this is an explicit specialization.
2052 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
2053
2054 // Check that this isn't a redefinition of this specialization.
2055 if (TK == TK_Definition) {
2056 if (RecordDecl *Def = Specialization->getDefinition(Context)) {
2057 // FIXME: Should also handle explicit specialization after
2058 // implicit instantiation with a special diagnostic.
2059 SourceRange Range(TemplateNameLoc, RAngleLoc);
2060 Diag(TemplateNameLoc, diag::err_redefinition)
2061 << Specialization << Range;
2062 Diag(Def->getLocation(), diag::note_previous_definition);
2063 Specialization->setInvalidDecl();
Douglas Gregor212e81c2009-03-25 00:13:59 +00002064 return true;
Douglas Gregorcc636682009-02-17 23:15:12 +00002065 }
2066 }
2067
Douglas Gregorfc705b82009-02-26 22:19:44 +00002068 // Build the fully-sugared type for this class template
2069 // specialization as the user wrote in the specialization
2070 // itself. This means that we'll pretty-print the type retrieved
2071 // from the specialization's declaration the way that the user
2072 // actually wrote the specialization, rather than formatting the
2073 // name based on the "canonical" representation used to store the
2074 // template arguments in the specialization.
Douglas Gregore6258932009-03-19 00:39:20 +00002075 QualType WrittenTy
Douglas Gregor7532dc62009-03-30 22:58:21 +00002076 = Context.getTemplateSpecializationType(Name,
2077 &TemplateArgs[0],
2078 TemplateArgs.size(),
Douglas Gregore6258932009-03-19 00:39:20 +00002079 Context.getTypeDeclType(Specialization));
Douglas Gregor7532dc62009-03-30 22:58:21 +00002080 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregor40808ce2009-03-09 23:48:35 +00002081 TemplateArgsIn.release();
Douglas Gregorcc636682009-02-17 23:15:12 +00002082
Douglas Gregor6bc9f7e2009-02-25 22:18:32 +00002083 // C++ [temp.expl.spec]p9:
2084 // A template explicit specialization is in the scope of the
2085 // namespace in which the template was defined.
2086 //
2087 // We actually implement this paragraph where we set the semantic
2088 // context (in the creation of the ClassTemplateSpecializationDecl),
2089 // but we also maintain the lexical context where the actual
2090 // definition occurs.
Douglas Gregorcc636682009-02-17 23:15:12 +00002091 Specialization->setLexicalDeclContext(CurContext);
2092
2093 // We may be starting the definition of this specialization.
2094 if (TK == TK_Definition)
2095 Specialization->startDefinition();
2096
2097 // Add the specialization into its lexical context, so that it can
2098 // be seen when iterating through the list of declarations in that
2099 // context. However, specializations are not found by name lookup.
Douglas Gregor6ab35242009-04-09 21:40:53 +00002100 CurContext->addDecl(Context, Specialization);
Chris Lattnerb28317a2009-03-28 19:18:32 +00002101 return DeclPtrTy::make(Specialization);
Douglas Gregorcc636682009-02-17 23:15:12 +00002102}
Douglas Gregord57959a2009-03-27 23:10:48 +00002103
2104Sema::TypeResult
2105Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
2106 const IdentifierInfo &II, SourceLocation IdLoc) {
2107 NestedNameSpecifier *NNS
2108 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
2109 if (!NNS)
2110 return true;
2111
2112 QualType T = CheckTypenameType(NNS, II, SourceRange(TypenameLoc, IdLoc));
Douglas Gregor31a19b62009-04-01 21:51:26 +00002113 if (T.isNull())
2114 return true;
Douglas Gregord57959a2009-03-27 23:10:48 +00002115 return T.getAsOpaquePtr();
2116}
2117
Douglas Gregor17343172009-04-01 00:28:59 +00002118Sema::TypeResult
2119Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
2120 SourceLocation TemplateLoc, TypeTy *Ty) {
2121 QualType T = QualType::getFromOpaquePtr(Ty);
2122 NestedNameSpecifier *NNS
2123 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
2124 const TemplateSpecializationType *TemplateId
2125 = T->getAsTemplateSpecializationType();
2126 assert(TemplateId && "Expected a template specialization type");
2127
2128 if (NNS->isDependent())
2129 return Context.getTypenameType(NNS, TemplateId).getAsOpaquePtr();
2130
2131 return Context.getQualifiedNameType(NNS, T).getAsOpaquePtr();
2132}
2133
Douglas Gregord57959a2009-03-27 23:10:48 +00002134/// \brief Build the type that describes a C++ typename specifier,
2135/// e.g., "typename T::type".
2136QualType
2137Sema::CheckTypenameType(NestedNameSpecifier *NNS, const IdentifierInfo &II,
2138 SourceRange Range) {
2139 if (NNS->isDependent()) // FIXME: member of the current instantiation!
2140 return Context.getTypenameType(NNS, &II);
2141
2142 CXXScopeSpec SS;
2143 SS.setScopeRep(NNS);
2144 SS.setRange(Range);
2145 if (RequireCompleteDeclContext(SS))
2146 return QualType();
2147
2148 DeclContext *Ctx = computeDeclContext(SS);
2149 assert(Ctx && "No declaration context?");
2150
2151 DeclarationName Name(&II);
2152 LookupResult Result = LookupQualifiedName(Ctx, Name, LookupOrdinaryName,
2153 false);
2154 unsigned DiagID = 0;
2155 Decl *Referenced = 0;
2156 switch (Result.getKind()) {
2157 case LookupResult::NotFound:
2158 if (Ctx->isTranslationUnit())
2159 DiagID = diag::err_typename_nested_not_found_global;
2160 else
2161 DiagID = diag::err_typename_nested_not_found;
2162 break;
2163
2164 case LookupResult::Found:
2165 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getAsDecl())) {
2166 // We found a type. Build a QualifiedNameType, since the
2167 // typename-specifier was just sugar. FIXME: Tell
2168 // QualifiedNameType that it has a "typename" prefix.
2169 return Context.getQualifiedNameType(NNS, Context.getTypeDeclType(Type));
2170 }
2171
2172 DiagID = diag::err_typename_nested_not_type;
2173 Referenced = Result.getAsDecl();
2174 break;
2175
2176 case LookupResult::FoundOverloaded:
2177 DiagID = diag::err_typename_nested_not_type;
2178 Referenced = *Result.begin();
2179 break;
2180
2181 case LookupResult::AmbiguousBaseSubobjectTypes:
2182 case LookupResult::AmbiguousBaseSubobjects:
2183 case LookupResult::AmbiguousReference:
2184 DiagnoseAmbiguousLookup(Result, Name, Range.getEnd(), Range);
2185 return QualType();
2186 }
2187
2188 // If we get here, it's because name lookup did not find a
2189 // type. Emit an appropriate diagnostic and return an error.
2190 if (NamedDecl *NamedCtx = dyn_cast<NamedDecl>(Ctx))
2191 Diag(Range.getEnd(), DiagID) << Range << Name << NamedCtx;
2192 else
2193 Diag(Range.getEnd(), DiagID) << Range << Name;
2194 if (Referenced)
2195 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
2196 << Name;
2197 return QualType();
2198}