blob: f03c1acb8e2d3dbfa4fc62f12824c8e99b8be077 [file] [log] [blame]
Douglas Gregordd861062008-12-05 18:15:24 +00001//===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===/
2
3//
4// The LLVM Compiler Infrastructure
5//
6// This file is distributed under the University of Illinois Open Source
7// License. See LICENSE.TXT for details.
Douglas Gregor74296542009-02-27 19:31:52 +00008//===----------------------------------------------------------------------===/
Douglas Gregordd861062008-12-05 18:15:24 +00009
10//
11// This file implements semantic analysis for C++ templates.
Douglas Gregor74296542009-02-27 19:31:52 +000012//===----------------------------------------------------------------------===/
Douglas Gregordd861062008-12-05 18:15:24 +000013
14#include "Sema.h"
Douglas Gregord406b032009-02-06 22:42:48 +000015#include "clang/AST/ASTContext.h"
Douglas Gregor1b21c7f2008-12-05 23:32:09 +000016#include "clang/AST/Expr.h"
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +000017#include "clang/AST/ExprCXX.h"
Douglas Gregor279272e2009-02-04 19:02:06 +000018#include "clang/AST/DeclTemplate.h"
Douglas Gregordd861062008-12-05 18:15:24 +000019#include "clang/Parse/DeclSpec.h"
20#include "clang/Basic/LangOptions.h"
21
22using namespace clang;
23
Douglas Gregor2fa10442008-12-18 19:37:40 +000024/// isTemplateName - Determines whether the identifier II is a
25/// template name in the current scope, and returns the template
26/// declaration if II names a template. An optional CXXScope can be
27/// passed to indicate the C++ scope in which the identifier will be
28/// found.
Douglas Gregoraabb8502009-03-31 00:43:58 +000029TemplateNameKind Sema::isTemplateName(const IdentifierInfo &II, Scope *S,
Douglas Gregordd13e842009-03-30 22:58:21 +000030 TemplateTy &TemplateResult,
Douglas Gregor0c281a82009-02-25 19:37:18 +000031 const CXXScopeSpec *SS) {
Douglas Gregor09be81b2009-02-04 17:27:36 +000032 NamedDecl *IIDecl = LookupParsedName(S, SS, &II, LookupOrdinaryName);
Douglas Gregor2fa10442008-12-18 19:37:40 +000033
Douglas Gregordd13e842009-03-30 22:58:21 +000034 TemplateNameKind TNK = TNK_Non_template;
35 TemplateDecl *Template = 0;
36
Douglas Gregor2fa10442008-12-18 19:37:40 +000037 if (IIDecl) {
Douglas Gregordd13e842009-03-30 22:58:21 +000038 if ((Template = dyn_cast<TemplateDecl>(IIDecl))) {
Douglas Gregor8e458f42009-02-09 18:46:07 +000039 if (isa<FunctionTemplateDecl>(IIDecl))
Douglas Gregordd13e842009-03-30 22:58:21 +000040 TNK = TNK_Function_template;
Douglas Gregoraabb8502009-03-31 00:43:58 +000041 else if (isa<ClassTemplateDecl>(IIDecl) ||
42 isa<TemplateTemplateParmDecl>(IIDecl))
43 TNK = TNK_Type_template;
Douglas Gregordd13e842009-03-30 22:58:21 +000044 else
45 assert(false && "Unknown template declaration kind");
Douglas Gregor55216ac2009-03-26 00:10:35 +000046 } else if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(IIDecl)) {
47 // C++ [temp.local]p1:
48 // Like normal (non-template) classes, class templates have an
49 // injected-class-name (Clause 9). The injected-class-name
50 // can be used with or without a template-argument-list. When
51 // it is used without a template-argument-list, it is
52 // equivalent to the injected-class-name followed by the
53 // template-parameters of the class template enclosed in
54 // <>. When it is used with a template-argument-list, it
55 // refers to the specified class template specialization,
56 // which could be the current specialization or another
57 // specialization.
58 if (Record->isInjectedClassName()) {
59 Record = cast<CXXRecordDecl>(Context.getCanonicalDecl(Record));
Douglas Gregordd13e842009-03-30 22:58:21 +000060 if ((Template = Record->getDescribedClassTemplate()))
Douglas Gregoraabb8502009-03-31 00:43:58 +000061 TNK = TNK_Type_template;
Douglas Gregordd13e842009-03-30 22:58:21 +000062 else if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor55216ac2009-03-26 00:10:35 +000063 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
Douglas Gregordd13e842009-03-30 22:58:21 +000064 Template = Spec->getSpecializedTemplate();
Douglas Gregoraabb8502009-03-31 00:43:58 +000065 TNK = TNK_Type_template;
Douglas Gregor55216ac2009-03-26 00:10:35 +000066 }
67 }
Douglas Gregor8e458f42009-02-09 18:46:07 +000068 }
Douglas Gregor279272e2009-02-04 19:02:06 +000069
Douglas Gregor8e458f42009-02-09 18:46:07 +000070 // FIXME: What follows is a gross hack.
Douglas Gregor2fa10442008-12-18 19:37:40 +000071 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(IIDecl)) {
Douglas Gregor8e458f42009-02-09 18:46:07 +000072 if (FD->getType()->isDependentType()) {
Douglas Gregordd13e842009-03-30 22:58:21 +000073 TemplateResult = TemplateTy::make(FD);
Douglas Gregor8e458f42009-02-09 18:46:07 +000074 return TNK_Function_template;
75 }
Douglas Gregor2fa10442008-12-18 19:37:40 +000076 } else if (OverloadedFunctionDecl *Ovl
77 = dyn_cast<OverloadedFunctionDecl>(IIDecl)) {
78 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
79 FEnd = Ovl->function_end();
80 F != FEnd; ++F) {
Douglas Gregor8e458f42009-02-09 18:46:07 +000081 if ((*F)->getType()->isDependentType()) {
Douglas Gregordd13e842009-03-30 22:58:21 +000082 TemplateResult = TemplateTy::make(Ovl);
Douglas Gregor8e458f42009-02-09 18:46:07 +000083 return TNK_Function_template;
84 }
Douglas Gregor2fa10442008-12-18 19:37:40 +000085 }
86 }
Douglas Gregordd13e842009-03-30 22:58:21 +000087
88 if (TNK != TNK_Non_template) {
89 if (SS && SS->isSet() && !SS->isInvalid()) {
90 NestedNameSpecifier *Qualifier
91 = static_cast<NestedNameSpecifier *>(SS->getScopeRep());
92 TemplateResult
93 = TemplateTy::make(Context.getQualifiedTemplateName(Qualifier,
94 false,
95 Template));
96 } else
97 TemplateResult = TemplateTy::make(TemplateName(Template));
98 }
Douglas Gregor2fa10442008-12-18 19:37:40 +000099 }
Douglas Gregordd13e842009-03-30 22:58:21 +0000100 return TNK;
Douglas Gregor2fa10442008-12-18 19:37:40 +0000101}
102
Douglas Gregordd861062008-12-05 18:15:24 +0000103/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
104/// that the template parameter 'PrevDecl' is being shadowed by a new
105/// declaration at location Loc. Returns true to indicate that this is
106/// an error, and false otherwise.
107bool Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
Douglas Gregor2715a1f2008-12-08 18:40:42 +0000108 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregordd861062008-12-05 18:15:24 +0000109
110 // Microsoft Visual C++ permits template parameters to be shadowed.
111 if (getLangOptions().Microsoft)
112 return false;
113
114 // C++ [temp.local]p4:
115 // A template-parameter shall not be redeclared within its
116 // scope (including nested scopes).
117 Diag(Loc, diag::err_template_param_shadow)
118 << cast<NamedDecl>(PrevDecl)->getDeclName();
119 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
120 return true;
121}
122
Douglas Gregored3a3982009-03-03 04:44:36 +0000123/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregor279272e2009-02-04 19:02:06 +0000124/// the parameter D to reference the templated declaration and return a pointer
125/// to the template declaration. Otherwise, do nothing to D and return null.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000126TemplateDecl *Sema::AdjustDeclIfTemplate(DeclPtrTy &D) {
127 if (TemplateDecl *Temp = dyn_cast<TemplateDecl>(D.getAs<Decl>())) {
128 D = DeclPtrTy::make(Temp->getTemplatedDecl());
Douglas Gregor279272e2009-02-04 19:02:06 +0000129 return Temp;
130 }
131 return 0;
132}
133
Douglas Gregordd861062008-12-05 18:15:24 +0000134/// ActOnTypeParameter - Called when a C++ template type parameter
135/// (e.g., "typename T") has been parsed. Typename specifies whether
136/// the keyword "typename" was used to declare the type parameter
137/// (otherwise, "class" was used), and KeyLoc is the location of the
138/// "class" or "typename" keyword. ParamName is the name of the
139/// parameter (NULL indicates an unnamed template parameter) and
140/// ParamName is the location of the parameter name (if any).
141/// If the type parameter has a default argument, it will be added
142/// later via ActOnTypeParameterDefault.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000143Sema::DeclPtrTy Sema::ActOnTypeParameter(Scope *S, bool Typename,
144 SourceLocation KeyLoc,
145 IdentifierInfo *ParamName,
146 SourceLocation ParamNameLoc,
147 unsigned Depth, unsigned Position) {
Douglas Gregordd861062008-12-05 18:15:24 +0000148 assert(S->isTemplateParamScope() &&
149 "Template type parameter not in template parameter scope!");
150 bool Invalid = false;
151
152 if (ParamName) {
Douglas Gregor09be81b2009-02-04 17:27:36 +0000153 NamedDecl *PrevDecl = LookupName(S, ParamName, LookupTagName);
Douglas Gregor2715a1f2008-12-08 18:40:42 +0000154 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregordd861062008-12-05 18:15:24 +0000155 Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc,
156 PrevDecl);
157 }
158
Douglas Gregord406b032009-02-06 22:42:48 +0000159 SourceLocation Loc = ParamNameLoc;
160 if (!ParamName)
161 Loc = KeyLoc;
162
Douglas Gregordd861062008-12-05 18:15:24 +0000163 TemplateTypeParmDecl *Param
Douglas Gregord406b032009-02-06 22:42:48 +0000164 = TemplateTypeParmDecl::Create(Context, CurContext, Loc,
Douglas Gregor279272e2009-02-04 19:02:06 +0000165 Depth, Position, ParamName, Typename);
Douglas Gregordd861062008-12-05 18:15:24 +0000166 if (Invalid)
167 Param->setInvalidDecl();
168
169 if (ParamName) {
170 // Add the template parameter into the current scope.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000171 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregordd861062008-12-05 18:15:24 +0000172 IdResolver.AddDecl(Param);
173 }
174
Chris Lattner5261d0c2009-03-28 19:18:32 +0000175 return DeclPtrTy::make(Param);
Douglas Gregordd861062008-12-05 18:15:24 +0000176}
177
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000178/// ActOnTypeParameterDefault - Adds a default argument (the type
179/// Default) to the given template type parameter (TypeParam).
Chris Lattner5261d0c2009-03-28 19:18:32 +0000180void Sema::ActOnTypeParameterDefault(DeclPtrTy TypeParam,
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000181 SourceLocation EqualLoc,
182 SourceLocation DefaultLoc,
183 TypeTy *DefaultT) {
184 TemplateTypeParmDecl *Parm
Chris Lattner5261d0c2009-03-28 19:18:32 +0000185 = cast<TemplateTypeParmDecl>(TypeParam.getAs<Decl>());
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000186 QualType Default = QualType::getFromOpaquePtr(DefaultT);
187
188 // C++ [temp.param]p14:
189 // A template-parameter shall not be used in its own default argument.
190 // FIXME: Implement this check! Needs a recursive walk over the types.
191
192 // Check the template argument itself.
193 if (CheckTemplateArgument(Parm, Default, DefaultLoc)) {
194 Parm->setInvalidDecl();
195 return;
196 }
197
198 Parm->setDefaultArgument(Default, DefaultLoc, false);
199}
200
Douglas Gregored3a3982009-03-03 04:44:36 +0000201/// \brief Check that the type of a non-type template parameter is
202/// well-formed.
203///
204/// \returns the (possibly-promoted) parameter type if valid;
205/// otherwise, produces a diagnostic and returns a NULL type.
206QualType
207Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
208 // C++ [temp.param]p4:
209 //
210 // A non-type template-parameter shall have one of the following
211 // (optionally cv-qualified) types:
212 //
213 // -- integral or enumeration type,
214 if (T->isIntegralType() || T->isEnumeralType() ||
215 // -- pointer to object or pointer to function,
216 (T->isPointerType() &&
217 (T->getAsPointerType()->getPointeeType()->isObjectType() ||
218 T->getAsPointerType()->getPointeeType()->isFunctionType())) ||
219 // -- reference to object or reference to function,
220 T->isReferenceType() ||
221 // -- pointer to member.
222 T->isMemberPointerType() ||
223 // If T is a dependent type, we can't do the check now, so we
224 // assume that it is well-formed.
225 T->isDependentType())
226 return T;
227 // C++ [temp.param]p8:
228 //
229 // A non-type template-parameter of type "array of T" or
230 // "function returning T" is adjusted to be of type "pointer to
231 // T" or "pointer to function returning T", respectively.
232 else if (T->isArrayType())
233 // FIXME: Keep the type prior to promotion?
234 return Context.getArrayDecayedType(T);
235 else if (T->isFunctionType())
236 // FIXME: Keep the type prior to promotion?
237 return Context.getPointerType(T);
238
239 Diag(Loc, diag::err_template_nontype_parm_bad_type)
240 << T;
241
242 return QualType();
243}
244
Douglas Gregordd861062008-12-05 18:15:24 +0000245/// ActOnNonTypeTemplateParameter - Called when a C++ non-type
246/// template parameter (e.g., "int Size" in "template<int Size>
247/// class Array") has been parsed. S is the current scope and D is
248/// the parsed declarator.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000249Sema::DeclPtrTy Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
250 unsigned Depth,
251 unsigned Position) {
Douglas Gregordd861062008-12-05 18:15:24 +0000252 QualType T = GetTypeForDeclarator(D, S);
253
Douglas Gregor279272e2009-02-04 19:02:06 +0000254 assert(S->isTemplateParamScope() &&
255 "Non-type template parameter not in template parameter scope!");
Douglas Gregordd861062008-12-05 18:15:24 +0000256 bool Invalid = false;
257
258 IdentifierInfo *ParamName = D.getIdentifier();
259 if (ParamName) {
Douglas Gregor09be81b2009-02-04 17:27:36 +0000260 NamedDecl *PrevDecl = LookupName(S, ParamName, LookupTagName);
Douglas Gregor2715a1f2008-12-08 18:40:42 +0000261 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregordd861062008-12-05 18:15:24 +0000262 Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
Douglas Gregor279272e2009-02-04 19:02:06 +0000263 PrevDecl);
Douglas Gregordd861062008-12-05 18:15:24 +0000264 }
265
Douglas Gregored3a3982009-03-03 04:44:36 +0000266 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
Douglas Gregor8b90e8e2009-03-09 16:46:39 +0000267 if (T.isNull()) {
Douglas Gregored3a3982009-03-03 04:44:36 +0000268 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregor8b90e8e2009-03-09 16:46:39 +0000269 Invalid = true;
270 }
Douglas Gregor62cdc792009-02-10 17:43:50 +0000271
Douglas Gregordd861062008-12-05 18:15:24 +0000272 NonTypeTemplateParmDecl *Param
273 = NonTypeTemplateParmDecl::Create(Context, CurContext, D.getIdentifierLoc(),
Douglas Gregor279272e2009-02-04 19:02:06 +0000274 Depth, Position, ParamName, T);
Douglas Gregordd861062008-12-05 18:15:24 +0000275 if (Invalid)
276 Param->setInvalidDecl();
277
278 if (D.getIdentifier()) {
279 // Add the template parameter into the current scope.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000280 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregordd861062008-12-05 18:15:24 +0000281 IdResolver.AddDecl(Param);
282 }
Chris Lattner5261d0c2009-03-28 19:18:32 +0000283 return DeclPtrTy::make(Param);
Douglas Gregordd861062008-12-05 18:15:24 +0000284}
Douglas Gregor52473432008-12-24 02:52:09 +0000285
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000286/// \brief Adds a default argument to the given non-type template
287/// parameter.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000288void Sema::ActOnNonTypeTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000289 SourceLocation EqualLoc,
290 ExprArg DefaultE) {
291 NonTypeTemplateParmDecl *TemplateParm
Chris Lattner5261d0c2009-03-28 19:18:32 +0000292 = cast<NonTypeTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000293 Expr *Default = static_cast<Expr *>(DefaultE.get());
294
295 // C++ [temp.param]p14:
296 // A template-parameter shall not be used in its own default argument.
297 // FIXME: Implement this check! Needs a recursive walk over the types.
298
299 // Check the well-formedness of the default template argument.
Douglas Gregored3a3982009-03-03 04:44:36 +0000300 if (CheckTemplateArgument(TemplateParm, TemplateParm->getType(), Default)) {
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000301 TemplateParm->setInvalidDecl();
302 return;
303 }
304
Anders Carlsson39ecdcf2009-05-01 19:49:17 +0000305 TemplateParm->setDefaultArgument(DefaultE.takeAs<Expr>());
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000306}
307
Douglas Gregor279272e2009-02-04 19:02:06 +0000308
309/// ActOnTemplateTemplateParameter - Called when a C++ template template
310/// parameter (e.g. T in template <template <typename> class T> class array)
311/// has been parsed. S is the current scope.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000312Sema::DeclPtrTy Sema::ActOnTemplateTemplateParameter(Scope* S,
313 SourceLocation TmpLoc,
314 TemplateParamsTy *Params,
315 IdentifierInfo *Name,
316 SourceLocation NameLoc,
317 unsigned Depth,
318 unsigned Position)
Douglas Gregor279272e2009-02-04 19:02:06 +0000319{
320 assert(S->isTemplateParamScope() &&
321 "Template template parameter not in template parameter scope!");
322
323 // Construct the parameter object.
324 TemplateTemplateParmDecl *Param =
325 TemplateTemplateParmDecl::Create(Context, CurContext, TmpLoc, Depth,
326 Position, Name,
327 (TemplateParameterList*)Params);
328
329 // Make sure the parameter is valid.
330 // FIXME: Decl object is not currently invalidated anywhere so this doesn't
331 // do anything yet. However, if the template parameter list or (eventual)
332 // default value is ever invalidated, that will propagate here.
333 bool Invalid = false;
334 if (Invalid) {
335 Param->setInvalidDecl();
336 }
337
338 // If the tt-param has a name, then link the identifier into the scope
339 // and lookup mechanisms.
340 if (Name) {
Chris Lattner5261d0c2009-03-28 19:18:32 +0000341 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor279272e2009-02-04 19:02:06 +0000342 IdResolver.AddDecl(Param);
343 }
344
Chris Lattner5261d0c2009-03-28 19:18:32 +0000345 return DeclPtrTy::make(Param);
Douglas Gregor279272e2009-02-04 19:02:06 +0000346}
347
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000348/// \brief Adds a default argument to the given template template
349/// parameter.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000350void Sema::ActOnTemplateTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000351 SourceLocation EqualLoc,
352 ExprArg DefaultE) {
353 TemplateTemplateParmDecl *TemplateParm
Chris Lattner5261d0c2009-03-28 19:18:32 +0000354 = cast<TemplateTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000355
356 // Since a template-template parameter's default argument is an
357 // id-expression, it must be a DeclRefExpr.
358 DeclRefExpr *Default
359 = cast<DeclRefExpr>(static_cast<Expr *>(DefaultE.get()));
360
361 // C++ [temp.param]p14:
362 // A template-parameter shall not be used in its own default argument.
363 // FIXME: Implement this check! Needs a recursive walk over the types.
364
365 // Check the well-formedness of the template argument.
366 if (!isa<TemplateDecl>(Default->getDecl())) {
367 Diag(Default->getSourceRange().getBegin(),
368 diag::err_template_arg_must_be_template)
369 << Default->getSourceRange();
370 TemplateParm->setInvalidDecl();
371 return;
372 }
373 if (CheckTemplateArgument(TemplateParm, Default)) {
374 TemplateParm->setInvalidDecl();
375 return;
376 }
377
378 DefaultE.release();
379 TemplateParm->setDefaultArgument(Default);
380}
381
Douglas Gregor52473432008-12-24 02:52:09 +0000382/// ActOnTemplateParameterList - Builds a TemplateParameterList that
383/// contains the template parameters in Params/NumParams.
384Sema::TemplateParamsTy *
385Sema::ActOnTemplateParameterList(unsigned Depth,
386 SourceLocation ExportLoc,
387 SourceLocation TemplateLoc,
388 SourceLocation LAngleLoc,
Chris Lattner5261d0c2009-03-28 19:18:32 +0000389 DeclPtrTy *Params, unsigned NumParams,
Douglas Gregor52473432008-12-24 02:52:09 +0000390 SourceLocation RAngleLoc) {
391 if (ExportLoc.isValid())
392 Diag(ExportLoc, diag::note_template_export_unsupported);
393
Douglas Gregord406b032009-02-06 22:42:48 +0000394 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
395 (Decl**)Params, NumParams, RAngleLoc);
Douglas Gregor52473432008-12-24 02:52:09 +0000396}
Douglas Gregor279272e2009-02-04 19:02:06 +0000397
Douglas Gregorc5d6fa72009-03-25 00:13:59 +0000398Sema::DeclResult
Douglas Gregord406b032009-02-06 22:42:48 +0000399Sema::ActOnClassTemplate(Scope *S, unsigned TagSpec, TagKind TK,
400 SourceLocation KWLoc, const CXXScopeSpec &SS,
401 IdentifierInfo *Name, SourceLocation NameLoc,
402 AttributeList *Attr,
Anders Carlssoned20fb92009-03-26 00:52:18 +0000403 MultiTemplateParamsArg TemplateParameterLists,
404 AccessSpecifier AS) {
Douglas Gregord406b032009-02-06 22:42:48 +0000405 assert(TemplateParameterLists.size() > 0 && "No template parameter lists?");
406 assert(TK != TK_Reference && "Can only declare or define class templates");
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000407 bool Invalid = false;
Douglas Gregord406b032009-02-06 22:42:48 +0000408
409 // Check that we can declare a template here.
410 if (CheckTemplateDeclScope(S, TemplateParameterLists))
Douglas Gregorc5d6fa72009-03-25 00:13:59 +0000411 return true;
Douglas Gregord406b032009-02-06 22:42:48 +0000412
413 TagDecl::TagKind Kind;
414 switch (TagSpec) {
415 default: assert(0 && "Unknown tag type!");
416 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
417 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
418 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
419 }
420
421 // There is no such thing as an unnamed class template.
422 if (!Name) {
423 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregorc5d6fa72009-03-25 00:13:59 +0000424 return true;
Douglas Gregord406b032009-02-06 22:42:48 +0000425 }
426
427 // Find any previous declaration with this name.
428 LookupResult Previous = LookupParsedName(S, &SS, Name, LookupOrdinaryName,
429 true);
430 assert(!Previous.isAmbiguous() && "Ambiguity in class template redecl?");
431 NamedDecl *PrevDecl = 0;
432 if (Previous.begin() != Previous.end())
433 PrevDecl = *Previous.begin();
434
435 DeclContext *SemanticContext = CurContext;
436 if (SS.isNotEmpty() && !SS.isInvalid()) {
Douglas Gregor734b4ba2009-03-19 00:18:19 +0000437 SemanticContext = computeDeclContext(SS);
Douglas Gregord406b032009-02-06 22:42:48 +0000438
Mike Stumpe127ae32009-05-16 07:39:55 +0000439 // FIXME: need to match up several levels of template parameter lists here.
Douglas Gregord406b032009-02-06 22:42:48 +0000440 }
441
442 // FIXME: member templates!
443 TemplateParameterList *TemplateParams
444 = static_cast<TemplateParameterList *>(*TemplateParameterLists.release());
445
446 // If there is a previous declaration with the same name, check
447 // whether this is a valid redeclaration.
448 ClassTemplateDecl *PrevClassTemplate
449 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
450 if (PrevClassTemplate) {
451 // Ensure that the template parameter lists are compatible.
452 if (!TemplateParameterListsAreEqual(TemplateParams,
453 PrevClassTemplate->getTemplateParameters(),
454 /*Complain=*/true))
Douglas Gregorc5d6fa72009-03-25 00:13:59 +0000455 return true;
Douglas Gregord406b032009-02-06 22:42:48 +0000456
457 // C++ [temp.class]p4:
458 // In a redeclaration, partial specialization, explicit
459 // specialization or explicit instantiation of a class template,
460 // the class-key shall agree in kind with the original class
461 // template declaration (7.1.5.3).
462 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Douglas Gregor625185c2009-05-14 16:41:31 +0000463 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind, KWLoc, *Name)) {
Douglas Gregor3faaa812009-04-01 23:51:29 +0000464 Diag(KWLoc, diag::err_use_with_wrong_tag)
465 << Name
466 << CodeModificationHint::CreateReplacement(KWLoc,
467 PrevRecordDecl->getKindName());
Douglas Gregord406b032009-02-06 22:42:48 +0000468 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregor3faaa812009-04-01 23:51:29 +0000469 Kind = PrevRecordDecl->getTagKind();
Douglas Gregord406b032009-02-06 22:42:48 +0000470 }
471
Douglas Gregord406b032009-02-06 22:42:48 +0000472 // Check for redefinition of this class template.
473 if (TK == TK_Definition) {
474 if (TagDecl *Def = PrevRecordDecl->getDefinition(Context)) {
475 Diag(NameLoc, diag::err_redefinition) << Name;
476 Diag(Def->getLocation(), diag::note_previous_definition);
477 // FIXME: Would it make sense to try to "forget" the previous
478 // definition, as part of error recovery?
Douglas Gregorc5d6fa72009-03-25 00:13:59 +0000479 return true;
Douglas Gregord406b032009-02-06 22:42:48 +0000480 }
481 }
482 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
483 // Maybe we will complain about the shadowed template parameter.
484 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
485 // Just pretend that we didn't see the previous declaration.
486 PrevDecl = 0;
487 } else if (PrevDecl) {
488 // C++ [temp]p5:
489 // A class template shall not have the same name as any other
490 // template, class, function, object, enumeration, enumerator,
491 // namespace, or type in the same scope (3.3), except as specified
492 // in (14.5.4).
493 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
494 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregorc5d6fa72009-03-25 00:13:59 +0000495 return true;
Douglas Gregord406b032009-02-06 22:42:48 +0000496 }
497
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000498 // Check the template parameter list of this declaration, possibly
499 // merging in the template parameter list from the previous class
500 // template declaration.
501 if (CheckTemplateParameterList(TemplateParams,
502 PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0))
503 Invalid = true;
504
Douglas Gregor9054f982009-05-10 22:57:19 +0000505 // FIXME: If we had a scope specifier, we better have a previous template
Douglas Gregord406b032009-02-06 22:42:48 +0000506 // declaration!
507
Douglas Gregor55216ac2009-03-26 00:10:35 +0000508 CXXRecordDecl *NewClass =
Douglas Gregord406b032009-02-06 22:42:48 +0000509 CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name,
510 PrevClassTemplate?
Douglas Gregor12aed0b2009-05-15 19:11:46 +0000511 PrevClassTemplate->getTemplatedDecl() : 0,
512 /*DelayTypeCreation=*/true);
Douglas Gregord406b032009-02-06 22:42:48 +0000513
514 ClassTemplateDecl *NewTemplate
515 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
516 DeclarationName(Name), TemplateParams,
Douglas Gregor47bde7c2009-03-19 17:26:29 +0000517 NewClass, PrevClassTemplate);
Douglas Gregor55216ac2009-03-26 00:10:35 +0000518 NewClass->setDescribedClassTemplate(NewTemplate);
519
Douglas Gregor12aed0b2009-05-15 19:11:46 +0000520 // Build the type for the class template declaration now.
521 QualType T =
522 Context.getTypeDeclType(NewClass,
523 PrevClassTemplate?
524 PrevClassTemplate->getTemplatedDecl() : 0);
525 assert(T->isDependentType() && "Class template type is not dependent?");
526 (void)T;
527
Anders Carlsson4ca43492009-03-26 01:24:28 +0000528 // Set the access specifier.
529 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
530
Douglas Gregord406b032009-02-06 22:42:48 +0000531 // Set the lexical context of these templates
532 NewClass->setLexicalDeclContext(CurContext);
533 NewTemplate->setLexicalDeclContext(CurContext);
534
535 if (TK == TK_Definition)
536 NewClass->startDefinition();
537
538 if (Attr)
539 ProcessDeclAttributeList(NewClass, Attr);
540
541 PushOnScopeChains(NewTemplate, S);
542
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000543 if (Invalid) {
544 NewTemplate->setInvalidDecl();
545 NewClass->setInvalidDecl();
546 }
Chris Lattner5261d0c2009-03-28 19:18:32 +0000547 return DeclPtrTy::make(NewTemplate);
Douglas Gregord406b032009-02-06 22:42:48 +0000548}
549
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000550/// \brief Checks the validity of a template parameter list, possibly
551/// considering the template parameter list from a previous
552/// declaration.
553///
554/// If an "old" template parameter list is provided, it must be
555/// equivalent (per TemplateParameterListsAreEqual) to the "new"
556/// template parameter list.
557///
558/// \param NewParams Template parameter list for a new template
559/// declaration. This template parameter list will be updated with any
560/// default arguments that are carried through from the previous
561/// template parameter list.
562///
563/// \param OldParams If provided, template parameter list from a
564/// previous declaration of the same template. Default template
565/// arguments will be merged from the old template parameter list to
566/// the new template parameter list.
567///
568/// \returns true if an error occurred, false otherwise.
569bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
570 TemplateParameterList *OldParams) {
571 bool Invalid = false;
572
573 // C++ [temp.param]p10:
574 // The set of default template-arguments available for use with a
575 // template declaration or definition is obtained by merging the
576 // default arguments from the definition (if in scope) and all
577 // declarations in scope in the same way default function
578 // arguments are (8.3.6).
579 bool SawDefaultArgument = false;
580 SourceLocation PreviousDefaultArgLoc;
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000581
Mike Stumpe0b7e032009-02-11 23:03:27 +0000582 // Dummy initialization to avoid warnings.
Douglas Gregorc5363f42009-02-11 20:46:19 +0000583 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000584 if (OldParams)
585 OldParam = OldParams->begin();
586
587 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
588 NewParamEnd = NewParams->end();
589 NewParam != NewParamEnd; ++NewParam) {
590 // Variables used to diagnose redundant default arguments
591 bool RedundantDefaultArg = false;
592 SourceLocation OldDefaultLoc;
593 SourceLocation NewDefaultLoc;
594
595 // Variables used to diagnose missing default arguments
596 bool MissingDefaultArg = false;
597
598 // Merge default arguments for template type parameters.
599 if (TemplateTypeParmDecl *NewTypeParm
600 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
601 TemplateTypeParmDecl *OldTypeParm
602 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
603
604 if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
605 NewTypeParm->hasDefaultArgument()) {
606 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
607 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
608 SawDefaultArgument = true;
609 RedundantDefaultArg = true;
610 PreviousDefaultArgLoc = NewDefaultLoc;
611 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
612 // Merge the default argument from the old declaration to the
613 // new declaration.
614 SawDefaultArgument = true;
615 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgument(),
616 OldTypeParm->getDefaultArgumentLoc(),
617 true);
618 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
619 } else if (NewTypeParm->hasDefaultArgument()) {
620 SawDefaultArgument = true;
621 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
622 } else if (SawDefaultArgument)
623 MissingDefaultArg = true;
624 }
625 // Merge default arguments for non-type template parameters
626 else if (NonTypeTemplateParmDecl *NewNonTypeParm
627 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
628 NonTypeTemplateParmDecl *OldNonTypeParm
629 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
630 if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
631 NewNonTypeParm->hasDefaultArgument()) {
632 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
633 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
634 SawDefaultArgument = true;
635 RedundantDefaultArg = true;
636 PreviousDefaultArgLoc = NewDefaultLoc;
637 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
638 // Merge the default argument from the old declaration to the
639 // new declaration.
640 SawDefaultArgument = true;
641 // FIXME: We need to create a new kind of "default argument"
642 // expression that points to a previous template template
643 // parameter.
644 NewNonTypeParm->setDefaultArgument(
645 OldNonTypeParm->getDefaultArgument());
646 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
647 } else if (NewNonTypeParm->hasDefaultArgument()) {
648 SawDefaultArgument = true;
649 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
650 } else if (SawDefaultArgument)
651 MissingDefaultArg = true;
652 }
653 // Merge default arguments for template template parameters
654 else {
655 TemplateTemplateParmDecl *NewTemplateParm
656 = cast<TemplateTemplateParmDecl>(*NewParam);
657 TemplateTemplateParmDecl *OldTemplateParm
658 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
659 if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
660 NewTemplateParm->hasDefaultArgument()) {
661 OldDefaultLoc = OldTemplateParm->getDefaultArgumentLoc();
662 NewDefaultLoc = NewTemplateParm->getDefaultArgumentLoc();
663 SawDefaultArgument = true;
664 RedundantDefaultArg = true;
665 PreviousDefaultArgLoc = NewDefaultLoc;
666 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
667 // Merge the default argument from the old declaration to the
668 // new declaration.
669 SawDefaultArgument = true;
Mike Stumpe127ae32009-05-16 07:39:55 +0000670 // FIXME: We need to create a new kind of "default argument" expression
671 // that points to a previous template template parameter.
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000672 NewTemplateParm->setDefaultArgument(
673 OldTemplateParm->getDefaultArgument());
674 PreviousDefaultArgLoc = OldTemplateParm->getDefaultArgumentLoc();
675 } else if (NewTemplateParm->hasDefaultArgument()) {
676 SawDefaultArgument = true;
677 PreviousDefaultArgLoc = NewTemplateParm->getDefaultArgumentLoc();
678 } else if (SawDefaultArgument)
679 MissingDefaultArg = true;
680 }
681
682 if (RedundantDefaultArg) {
683 // C++ [temp.param]p12:
684 // A template-parameter shall not be given default arguments
685 // by two different declarations in the same scope.
686 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
687 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
688 Invalid = true;
689 } else if (MissingDefaultArg) {
690 // C++ [temp.param]p11:
691 // If a template-parameter has a default template-argument,
692 // all subsequent template-parameters shall have a default
693 // template-argument supplied.
694 Diag((*NewParam)->getLocation(),
695 diag::err_template_param_default_arg_missing);
696 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
697 Invalid = true;
698 }
699
700 // If we have an old template parameter list that we're merging
701 // in, move on to the next parameter.
702 if (OldParams)
703 ++OldParam;
704 }
705
706 return Invalid;
707}
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000708
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000709/// \brief Translates template arguments as provided by the parser
710/// into template arguments used by semantic analysis.
711static void
712translateTemplateArguments(ASTTemplateArgsPtr &TemplateArgsIn,
713 SourceLocation *TemplateArgLocs,
714 llvm::SmallVector<TemplateArgument, 16> &TemplateArgs) {
715 TemplateArgs.reserve(TemplateArgsIn.size());
716
717 void **Args = TemplateArgsIn.getArgs();
718 bool *ArgIsType = TemplateArgsIn.getArgIsType();
719 for (unsigned Arg = 0, Last = TemplateArgsIn.size(); Arg != Last; ++Arg) {
720 TemplateArgs.push_back(
721 ArgIsType[Arg]? TemplateArgument(TemplateArgLocs[Arg],
722 QualType::getFromOpaquePtr(Args[Arg]))
723 : TemplateArgument(reinterpret_cast<Expr *>(Args[Arg])));
724 }
725}
726
Douglas Gregoraabb8502009-03-31 00:43:58 +0000727/// \brief Build a canonical version of a template argument list.
728///
729/// This function builds a canonical version of the given template
730/// argument list, where each of the template arguments has been
731/// converted into its canonical form. This routine is typically used
732/// to canonicalize a template argument list when the template name
733/// itself is dependent. When the template name refers to an actual
734/// template declaration, Sema::CheckTemplateArgumentList should be
735/// used to check and canonicalize the template arguments.
736///
737/// \param TemplateArgs The incoming template arguments.
738///
739/// \param NumTemplateArgs The number of template arguments in \p
740/// TemplateArgs.
741///
742/// \param Canonical A vector to be filled with the canonical versions
743/// of the template arguments.
744///
745/// \param Context The ASTContext in which the template arguments live.
746static void CanonicalizeTemplateArguments(const TemplateArgument *TemplateArgs,
747 unsigned NumTemplateArgs,
748 llvm::SmallVectorImpl<TemplateArgument> &Canonical,
749 ASTContext &Context) {
750 Canonical.reserve(NumTemplateArgs);
751 for (unsigned Idx = 0; Idx < NumTemplateArgs; ++Idx) {
752 switch (TemplateArgs[Idx].getKind()) {
Douglas Gregorbf23a8a2009-06-04 00:03:07 +0000753 case TemplateArgument::Null:
754 assert(false && "Should never see a NULL template argument here");
755 break;
756
Douglas Gregoraabb8502009-03-31 00:43:58 +0000757 case TemplateArgument::Expression:
758 // FIXME: Build canonical expression (!)
759 Canonical.push_back(TemplateArgs[Idx]);
760 break;
761
762 case TemplateArgument::Declaration:
Douglas Gregor9054f982009-05-10 22:57:19 +0000763 Canonical.push_back(
764 TemplateArgument(SourceLocation(),
765 Context.getCanonicalDecl(TemplateArgs[Idx].getAsDecl())));
Douglas Gregoraabb8502009-03-31 00:43:58 +0000766 break;
767
768 case TemplateArgument::Integral:
769 Canonical.push_back(TemplateArgument(SourceLocation(),
770 *TemplateArgs[Idx].getAsIntegral(),
771 TemplateArgs[Idx].getIntegralType()));
Douglas Gregorbf23a8a2009-06-04 00:03:07 +0000772 break;
Douglas Gregoraabb8502009-03-31 00:43:58 +0000773
774 case TemplateArgument::Type: {
775 QualType CanonType
776 = Context.getCanonicalType(TemplateArgs[Idx].getAsType());
777 Canonical.push_back(TemplateArgument(SourceLocation(), CanonType));
Douglas Gregorbf23a8a2009-06-04 00:03:07 +0000778 break;
Douglas Gregoraabb8502009-03-31 00:43:58 +0000779 }
780 }
781 }
782}
783
Douglas Gregordd13e842009-03-30 22:58:21 +0000784QualType Sema::CheckTemplateIdType(TemplateName Name,
785 SourceLocation TemplateLoc,
786 SourceLocation LAngleLoc,
787 const TemplateArgument *TemplateArgs,
788 unsigned NumTemplateArgs,
789 SourceLocation RAngleLoc) {
790 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregoraabb8502009-03-31 00:43:58 +0000791 if (!Template) {
792 // The template name does not resolve to a template, so we just
793 // build a dependent template-id type.
794
795 // Canonicalize the template arguments to build the canonical
796 // template-id type.
797 llvm::SmallVector<TemplateArgument, 16> CanonicalTemplateArgs;
798 CanonicalizeTemplateArguments(TemplateArgs, NumTemplateArgs,
799 CanonicalTemplateArgs, Context);
800
Douglas Gregor905406b2009-05-07 06:49:52 +0000801 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
Douglas Gregoraabb8502009-03-31 00:43:58 +0000802 QualType CanonType
Douglas Gregor905406b2009-05-07 06:49:52 +0000803 = Context.getTemplateSpecializationType(CanonName,
804 &CanonicalTemplateArgs[0],
Douglas Gregoraabb8502009-03-31 00:43:58 +0000805 CanonicalTemplateArgs.size());
806
807 // Build the dependent template-id type.
808 return Context.getTemplateSpecializationType(Name, TemplateArgs,
809 NumTemplateArgs, CanonType);
810 }
Douglas Gregordd13e842009-03-30 22:58:21 +0000811
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000812 // Check that the template argument list is well-formed for this
813 // template.
Anders Carlsson558a3a32009-06-05 05:31:27 +0000814 TemplateArgumentListBuilder ConvertedTemplateArgs(Context);
Douglas Gregordd13e842009-03-30 22:58:21 +0000815 if (CheckTemplateArgumentList(Template, TemplateLoc, LAngleLoc,
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000816 TemplateArgs, NumTemplateArgs, RAngleLoc,
817 ConvertedTemplateArgs))
818 return QualType();
819
820 assert((ConvertedTemplateArgs.size() ==
Douglas Gregordd13e842009-03-30 22:58:21 +0000821 Template->getTemplateParameters()->size()) &&
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000822 "Converted template argument list is too short!");
823
824 QualType CanonType;
825
Douglas Gregordd13e842009-03-30 22:58:21 +0000826 if (TemplateSpecializationType::anyDependentTemplateArguments(
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000827 TemplateArgs,
828 NumTemplateArgs)) {
829 // This class template specialization is a dependent
830 // type. Therefore, its canonical type is another class template
831 // specialization type that contains all of the converted
832 // arguments in canonical form. This ensures that, e.g., A<T> and
833 // A<T, T> have identical types when A is declared as:
834 //
835 // template<typename T, typename U = T> struct A;
Douglas Gregorb88ba412009-05-07 06:41:52 +0000836 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
837 CanonType = Context.getTemplateSpecializationType(CanonName,
Anders Carlssona35faf92009-06-05 03:43:12 +0000838 ConvertedTemplateArgs.getFlatArgumentList(),
839 ConvertedTemplateArgs.flatSize());
Douglas Gregordd13e842009-03-30 22:58:21 +0000840 } else if (ClassTemplateDecl *ClassTemplate
841 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000842 // Find the class template specialization declaration that
843 // corresponds to these arguments.
844 llvm::FoldingSetNodeID ID;
Anders Carlssona35faf92009-06-05 03:43:12 +0000845 ClassTemplateSpecializationDecl::Profile(ID,
846 ConvertedTemplateArgs.getFlatArgumentList(),
847 ConvertedTemplateArgs.flatSize());
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000848 void *InsertPos = 0;
849 ClassTemplateSpecializationDecl *Decl
850 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
851 if (!Decl) {
852 // This is the first time we have referenced this class template
853 // specialization. Create the canonical declaration and add it to
854 // the set of specializations.
855 Decl = ClassTemplateSpecializationDecl::Create(Context,
Anders Carlssona35faf92009-06-05 03:43:12 +0000856 ClassTemplate->getDeclContext(),
857 TemplateLoc,
858 ClassTemplate,
Anders Carlsson6e9d02f2009-06-05 04:06:48 +0000859 ConvertedTemplateArgs, 0);
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000860 ClassTemplate->getSpecializations().InsertNode(Decl, InsertPos);
861 Decl->setLexicalDeclContext(CurContext);
862 }
863
864 CanonType = Context.getTypeDeclType(Decl);
865 }
866
867 // Build the fully-sugared type for this class template
868 // specialization, which refers back to the class template
869 // specialization we created or found.
Douglas Gregordd13e842009-03-30 22:58:21 +0000870 return Context.getTemplateSpecializationType(Name, TemplateArgs,
871 NumTemplateArgs, CanonType);
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000872}
873
Douglas Gregora08b6c72009-02-17 23:15:12 +0000874Action::TypeResult
Douglas Gregordd13e842009-03-30 22:58:21 +0000875Sema::ActOnTemplateIdType(TemplateTy TemplateD, SourceLocation TemplateLoc,
876 SourceLocation LAngleLoc,
877 ASTTemplateArgsPtr TemplateArgsIn,
878 SourceLocation *TemplateArgLocs,
879 SourceLocation RAngleLoc) {
880 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Douglas Gregor8e458f42009-02-09 18:46:07 +0000881
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000882 // Translate the parser's template argument list in our AST format.
883 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
884 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000885
Douglas Gregordd13e842009-03-30 22:58:21 +0000886 QualType Result = CheckTemplateIdType(Template, TemplateLoc, LAngleLoc,
Jay Foad9e6bef42009-05-21 09:52:38 +0000887 TemplateArgs.data(),
888 TemplateArgs.size(),
Douglas Gregordd13e842009-03-30 22:58:21 +0000889 RAngleLoc);
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000890 TemplateArgsIn.release();
Douglas Gregord7cb0372009-04-01 21:51:26 +0000891
892 if (Result.isNull())
893 return true;
894
Douglas Gregor6f37b582009-02-09 19:34:22 +0000895 return Result.getAsOpaquePtr();
Douglas Gregor8e458f42009-02-09 18:46:07 +0000896}
897
Douglas Gregoraabb8502009-03-31 00:43:58 +0000898/// \brief Form a dependent template name.
899///
900/// This action forms a dependent template name given the template
901/// name and its (presumably dependent) scope specifier. For
902/// example, given "MetaFun::template apply", the scope specifier \p
903/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
904/// of the "template" keyword, and "apply" is the \p Name.
905Sema::TemplateTy
906Sema::ActOnDependentTemplateName(SourceLocation TemplateKWLoc,
907 const IdentifierInfo &Name,
908 SourceLocation NameLoc,
909 const CXXScopeSpec &SS) {
910 if (!SS.isSet() || SS.isInvalid())
911 return TemplateTy();
912
913 NestedNameSpecifier *Qualifier
914 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
915
916 // FIXME: member of the current instantiation
917
918 if (!Qualifier->isDependent()) {
919 // C++0x [temp.names]p5:
920 // If a name prefixed by the keyword template is not the name of
921 // a template, the program is ill-formed. [Note: the keyword
922 // template may not be applied to non-template members of class
923 // templates. -end note ] [ Note: as is the case with the
924 // typename prefix, the template prefix is allowed in cases
925 // where it is not strictly necessary; i.e., when the
926 // nested-name-specifier or the expression on the left of the ->
927 // or . is not dependent on a template-parameter, or the use
928 // does not appear in the scope of a template. -end note]
929 //
930 // Note: C++03 was more strict here, because it banned the use of
931 // the "template" keyword prior to a template-name that was not a
932 // dependent name. C++ DR468 relaxed this requirement (the
933 // "template" keyword is now permitted). We follow the C++0x
934 // rules, even in C++03 mode, retroactively applying the DR.
935 TemplateTy Template;
936 TemplateNameKind TNK = isTemplateName(Name, 0, Template, &SS);
937 if (TNK == TNK_Non_template) {
938 Diag(NameLoc, diag::err_template_kw_refers_to_non_template)
939 << &Name;
940 return TemplateTy();
941 }
942
943 return Template;
944 }
945
946 return TemplateTy::make(Context.getDependentTemplateName(Qualifier, &Name));
947}
948
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000949/// \brief Check that the given template argument list is well-formed
950/// for specializing the given template.
951bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
952 SourceLocation TemplateLoc,
953 SourceLocation LAngleLoc,
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000954 const TemplateArgument *TemplateArgs,
955 unsigned NumTemplateArgs,
Douglas Gregorad964b32009-02-17 01:05:43 +0000956 SourceLocation RAngleLoc,
Anders Carlssona35faf92009-06-05 03:43:12 +0000957 TemplateArgumentListBuilder &Converted) {
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000958 TemplateParameterList *Params = Template->getTemplateParameters();
959 unsigned NumParams = Params->size();
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000960 unsigned NumArgs = NumTemplateArgs;
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000961 bool Invalid = false;
962
963 if (NumArgs > NumParams ||
Douglas Gregorc347d8e2009-02-11 18:16:40 +0000964 NumArgs < Params->getMinRequiredArguments()) {
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000965 // FIXME: point at either the first arg beyond what we can handle,
966 // or the '>', depending on whether we have too many or too few
967 // arguments.
968 SourceRange Range;
969 if (NumArgs > NumParams)
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000970 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000971 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
972 << (NumArgs > NumParams)
973 << (isa<ClassTemplateDecl>(Template)? 0 :
974 isa<FunctionTemplateDecl>(Template)? 1 :
975 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
976 << Template << Range;
Douglas Gregorc347d8e2009-02-11 18:16:40 +0000977 Diag(Template->getLocation(), diag::note_template_decl_here)
978 << Params->getSourceRange();
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000979 Invalid = true;
980 }
981
982 // C++ [temp.arg]p1:
983 // [...] The type and form of each template-argument specified in
984 // a template-id shall match the type and form specified for the
985 // corresponding parameter declared by the template in its
986 // template-parameter-list.
987 unsigned ArgIdx = 0;
988 for (TemplateParameterList::iterator Param = Params->begin(),
989 ParamEnd = Params->end();
990 Param != ParamEnd; ++Param, ++ArgIdx) {
991 // Decode the template argument
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000992 TemplateArgument Arg;
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000993 if (ArgIdx >= NumArgs) {
Douglas Gregorad964b32009-02-17 01:05:43 +0000994 // Retrieve the default template argument from the template
995 // parameter.
996 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
997 if (!TTP->hasDefaultArgument())
998 break;
999
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001000 QualType ArgType = TTP->getDefaultArgument();
Douglas Gregor74296542009-02-27 19:31:52 +00001001
1002 // If the argument type is dependent, instantiate it now based
1003 // on the previously-computed template arguments.
Douglas Gregor56d25a72009-03-10 20:44:00 +00001004 if (ArgType->isDependentType()) {
1005 InstantiatingTemplate Inst(*this, TemplateLoc,
Anders Carlssona35faf92009-06-05 03:43:12 +00001006 Template, Converted.getFlatArgumentList(),
1007 Converted.flatSize(),
Douglas Gregor56d25a72009-03-10 20:44:00 +00001008 SourceRange(TemplateLoc, RAngleLoc));
Douglas Gregorf9e7d3d2009-05-11 23:53:27 +00001009
Anders Carlsson0233eb62009-06-05 04:47:51 +00001010 TemplateArgumentList TemplateArgs(Context, Converted,
1011 /*CopyArgs=*/false,
1012 /*FlattenArgs=*/false);
Douglas Gregorf9e7d3d2009-05-11 23:53:27 +00001013 ArgType = InstantiateType(ArgType, TemplateArgs,
Douglas Gregor74296542009-02-27 19:31:52 +00001014 TTP->getDefaultArgumentLoc(),
1015 TTP->getDeclName());
Douglas Gregor56d25a72009-03-10 20:44:00 +00001016 }
Douglas Gregor74296542009-02-27 19:31:52 +00001017
1018 if (ArgType.isNull())
Douglas Gregorf57dcd02009-02-28 00:25:32 +00001019 return true;
Douglas Gregor74296542009-02-27 19:31:52 +00001020
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001021 Arg = TemplateArgument(TTP->getLocation(), ArgType);
Douglas Gregorad964b32009-02-17 01:05:43 +00001022 } else if (NonTypeTemplateParmDecl *NTTP
1023 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
1024 if (!NTTP->hasDefaultArgument())
1025 break;
1026
Anders Carlsson0297caf2009-06-11 16:06:49 +00001027 InstantiatingTemplate Inst(*this, TemplateLoc,
1028 Template, Converted.getFlatArgumentList(),
1029 Converted.flatSize(),
1030 SourceRange(TemplateLoc, RAngleLoc));
1031
1032 TemplateArgumentList TemplateArgs(Context, Converted,
1033 /*CopyArgs=*/false,
1034 /*FlattenArgs=*/false);
1035
1036 Sema::OwningExprResult E = InstantiateExpr(NTTP->getDefaultArgument(),
1037 TemplateArgs);
1038 if (E.isInvalid())
1039 return true;
1040
1041 Arg = TemplateArgument(E.takeAs<Expr>());
Douglas Gregorad964b32009-02-17 01:05:43 +00001042 } else {
1043 TemplateTemplateParmDecl *TempParm
1044 = cast<TemplateTemplateParmDecl>(*Param);
1045
1046 if (!TempParm->hasDefaultArgument())
1047 break;
1048
Douglas Gregored3a3982009-03-03 04:44:36 +00001049 // FIXME: Instantiate default argument
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001050 Arg = TemplateArgument(TempParm->getDefaultArgument());
Douglas Gregorad964b32009-02-17 01:05:43 +00001051 }
1052 } else {
1053 // Retrieve the template argument produced by the user.
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001054 Arg = TemplateArgs[ArgIdx];
Douglas Gregorad964b32009-02-17 01:05:43 +00001055 }
1056
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001057
1058 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
1059 // Check template type parameters.
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001060 if (Arg.getKind() == TemplateArgument::Type) {
1061 if (CheckTemplateArgument(TTP, Arg.getAsType(), Arg.getLocation()))
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001062 Invalid = true;
Douglas Gregorad964b32009-02-17 01:05:43 +00001063
1064 // Add the converted template type argument.
1065 Converted.push_back(
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001066 TemplateArgument(Arg.getLocation(),
1067 Context.getCanonicalType(Arg.getAsType())));
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001068 continue;
1069 }
1070
1071 // C++ [temp.arg.type]p1:
1072 // A template-argument for a template-parameter which is a
1073 // type shall be a type-id.
1074
1075 // We have a template type parameter but the template argument
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001076 // is not a type.
1077 Diag(Arg.getLocation(), diag::err_template_arg_must_be_type);
Douglas Gregor341ac792009-02-10 00:53:15 +00001078 Diag((*Param)->getLocation(), diag::note_template_param_here);
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001079 Invalid = true;
1080 } else if (NonTypeTemplateParmDecl *NTTP
1081 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
1082 // Check non-type template parameters.
Douglas Gregored3a3982009-03-03 04:44:36 +00001083
1084 // Instantiate the type of the non-type template parameter with
1085 // the template arguments we've seen thus far.
1086 QualType NTTPType = NTTP->getType();
1087 if (NTTPType->isDependentType()) {
1088 // Instantiate the type of the non-type template parameter.
Douglas Gregor56d25a72009-03-10 20:44:00 +00001089 InstantiatingTemplate Inst(*this, TemplateLoc,
Anders Carlssona35faf92009-06-05 03:43:12 +00001090 Template, Converted.getFlatArgumentList(),
1091 Converted.flatSize(),
Douglas Gregor56d25a72009-03-10 20:44:00 +00001092 SourceRange(TemplateLoc, RAngleLoc));
1093
Anders Carlsson0233eb62009-06-05 04:47:51 +00001094 TemplateArgumentList TemplateArgs(Context, Converted,
1095 /*CopyArgs=*/false,
1096 /*FlattenArgs=*/false);
Douglas Gregorf9e7d3d2009-05-11 23:53:27 +00001097 NTTPType = InstantiateType(NTTPType, TemplateArgs,
Douglas Gregored3a3982009-03-03 04:44:36 +00001098 NTTP->getLocation(),
1099 NTTP->getDeclName());
1100 // If that worked, check the non-type template parameter type
1101 // for validity.
1102 if (!NTTPType.isNull())
1103 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
1104 NTTP->getLocation());
1105
1106 if (NTTPType.isNull()) {
1107 Invalid = true;
1108 break;
1109 }
1110 }
1111
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001112 switch (Arg.getKind()) {
Douglas Gregorbf23a8a2009-06-04 00:03:07 +00001113 case TemplateArgument::Null:
1114 assert(false && "Should never see a NULL template argument here");
1115 break;
1116
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001117 case TemplateArgument::Expression: {
1118 Expr *E = Arg.getAsExpr();
1119 if (CheckTemplateArgument(NTTP, NTTPType, E, &Converted))
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001120 Invalid = true;
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001121 break;
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001122 }
1123
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001124 case TemplateArgument::Declaration:
1125 case TemplateArgument::Integral:
1126 // We've already checked this template argument, so just copy
1127 // it to the list of converted arguments.
1128 Converted.push_back(Arg);
1129 break;
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001130
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001131 case TemplateArgument::Type:
1132 // We have a non-type template parameter but the template
1133 // argument is a type.
1134
1135 // C++ [temp.arg]p2:
1136 // In a template-argument, an ambiguity between a type-id and
1137 // an expression is resolved to a type-id, regardless of the
1138 // form of the corresponding template-parameter.
1139 //
1140 // We warn specifically about this case, since it can be rather
1141 // confusing for users.
1142 if (Arg.getAsType()->isFunctionType())
1143 Diag(Arg.getLocation(), diag::err_template_arg_nontype_ambig)
1144 << Arg.getAsType();
1145 else
1146 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr);
1147 Diag((*Param)->getLocation(), diag::note_template_param_here);
1148 Invalid = true;
1149 }
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001150 } else {
1151 // Check template template parameters.
1152 TemplateTemplateParmDecl *TempParm
1153 = cast<TemplateTemplateParmDecl>(*Param);
1154
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001155 switch (Arg.getKind()) {
Douglas Gregorbf23a8a2009-06-04 00:03:07 +00001156 case TemplateArgument::Null:
1157 assert(false && "Should never see a NULL template argument here");
1158 break;
1159
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001160 case TemplateArgument::Expression: {
1161 Expr *ArgExpr = Arg.getAsExpr();
1162 if (ArgExpr && isa<DeclRefExpr>(ArgExpr) &&
1163 isa<TemplateDecl>(cast<DeclRefExpr>(ArgExpr)->getDecl())) {
1164 if (CheckTemplateArgument(TempParm, cast<DeclRefExpr>(ArgExpr)))
1165 Invalid = true;
1166
1167 // Add the converted template argument.
Douglas Gregor9054f982009-05-10 22:57:19 +00001168 Decl *D
1169 = Context.getCanonicalDecl(cast<DeclRefExpr>(ArgExpr)->getDecl());
1170 Converted.push_back(TemplateArgument(Arg.getLocation(), D));
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001171 continue;
1172 }
1173 }
1174 // fall through
1175
1176 case TemplateArgument::Type: {
1177 // We have a template template parameter but the template
1178 // argument does not refer to a template.
1179 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
1180 Invalid = true;
1181 break;
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001182 }
1183
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001184 case TemplateArgument::Declaration:
1185 // We've already checked this template argument, so just copy
1186 // it to the list of converted arguments.
1187 Converted.push_back(Arg);
1188 break;
1189
1190 case TemplateArgument::Integral:
1191 assert(false && "Integral argument with template template parameter");
1192 break;
1193 }
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001194 }
1195 }
1196
1197 return Invalid;
1198}
1199
1200/// \brief Check a template argument against its corresponding
1201/// template type parameter.
1202///
1203/// This routine implements the semantics of C++ [temp.arg.type]. It
1204/// returns true if an error occurred, and false otherwise.
1205bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
1206 QualType Arg, SourceLocation ArgLoc) {
1207 // C++ [temp.arg.type]p2:
1208 // A local type, a type with no linkage, an unnamed type or a type
1209 // compounded from any of these types shall not be used as a
1210 // template-argument for a template type-parameter.
1211 //
1212 // FIXME: Perform the recursive and no-linkage type checks.
1213 const TagType *Tag = 0;
1214 if (const EnumType *EnumT = Arg->getAsEnumType())
1215 Tag = EnumT;
1216 else if (const RecordType *RecordT = Arg->getAsRecordType())
1217 Tag = RecordT;
1218 if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod())
1219 return Diag(ArgLoc, diag::err_template_arg_local_type)
1220 << QualType(Tag, 0);
Douglas Gregor04385782009-03-10 18:33:27 +00001221 else if (Tag && !Tag->getDecl()->getDeclName() &&
1222 !Tag->getDecl()->getTypedefForAnonDecl()) {
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001223 Diag(ArgLoc, diag::err_template_arg_unnamed_type);
1224 Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here);
1225 return true;
1226 }
1227
1228 return false;
1229}
1230
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001231/// \brief Checks whether the given template argument is the address
1232/// of an object or function according to C++ [temp.arg.nontype]p1.
Douglas Gregorad964b32009-02-17 01:05:43 +00001233bool Sema::CheckTemplateArgumentAddressOfObjectOrFunction(Expr *Arg,
1234 NamedDecl *&Entity) {
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001235 bool Invalid = false;
1236
1237 // See through any implicit casts we added to fix the type.
1238 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
1239 Arg = Cast->getSubExpr();
1240
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001241 // C++0x allows nullptr, and there's no further checking to be done for that.
1242 if (Arg->getType()->isNullPtrType())
1243 return false;
1244
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001245 // C++ [temp.arg.nontype]p1:
1246 //
1247 // A template-argument for a non-type, non-template
1248 // template-parameter shall be one of: [...]
1249 //
1250 // -- the address of an object or function with external
1251 // linkage, including function templates and function
1252 // template-ids but excluding non-static class members,
1253 // expressed as & id-expression where the & is optional if
1254 // the name refers to a function or array, or if the
1255 // corresponding template-parameter is a reference; or
1256 DeclRefExpr *DRE = 0;
1257
1258 // Ignore (and complain about) any excess parentheses.
1259 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
1260 if (!Invalid) {
1261 Diag(Arg->getSourceRange().getBegin(),
1262 diag::err_template_arg_extra_parens)
1263 << Arg->getSourceRange();
1264 Invalid = true;
1265 }
1266
1267 Arg = Parens->getSubExpr();
1268 }
1269
1270 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
1271 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
1272 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
1273 } else
1274 DRE = dyn_cast<DeclRefExpr>(Arg);
1275
1276 if (!DRE || !isa<ValueDecl>(DRE->getDecl()))
1277 return Diag(Arg->getSourceRange().getBegin(),
1278 diag::err_template_arg_not_object_or_func_form)
1279 << Arg->getSourceRange();
1280
1281 // Cannot refer to non-static data members
1282 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl()))
1283 return Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
1284 << Field << Arg->getSourceRange();
1285
1286 // Cannot refer to non-static member functions
1287 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
1288 if (!Method->isStatic())
1289 return Diag(Arg->getSourceRange().getBegin(),
1290 diag::err_template_arg_method)
1291 << Method << Arg->getSourceRange();
1292
1293 // Functions must have external linkage.
1294 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
1295 if (Func->getStorageClass() == FunctionDecl::Static) {
1296 Diag(Arg->getSourceRange().getBegin(),
1297 diag::err_template_arg_function_not_extern)
1298 << Func << Arg->getSourceRange();
1299 Diag(Func->getLocation(), diag::note_template_arg_internal_object)
1300 << true;
1301 return true;
1302 }
1303
1304 // Okay: we've named a function with external linkage.
Douglas Gregorad964b32009-02-17 01:05:43 +00001305 Entity = Func;
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001306 return Invalid;
1307 }
1308
1309 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
1310 if (!Var->hasGlobalStorage()) {
1311 Diag(Arg->getSourceRange().getBegin(),
1312 diag::err_template_arg_object_not_extern)
1313 << Var << Arg->getSourceRange();
1314 Diag(Var->getLocation(), diag::note_template_arg_internal_object)
1315 << true;
1316 return true;
1317 }
1318
1319 // Okay: we've named an object with external linkage
Douglas Gregorad964b32009-02-17 01:05:43 +00001320 Entity = Var;
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001321 return Invalid;
1322 }
1323
1324 // We found something else, but we don't know specifically what it is.
1325 Diag(Arg->getSourceRange().getBegin(),
1326 diag::err_template_arg_not_object_or_func)
1327 << Arg->getSourceRange();
1328 Diag(DRE->getDecl()->getLocation(),
1329 diag::note_template_arg_refers_here);
1330 return true;
1331}
1332
1333/// \brief Checks whether the given template argument is a pointer to
1334/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregorad964b32009-02-17 01:05:43 +00001335bool
1336Sema::CheckTemplateArgumentPointerToMember(Expr *Arg, NamedDecl *&Member) {
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001337 bool Invalid = false;
1338
1339 // See through any implicit casts we added to fix the type.
1340 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
1341 Arg = Cast->getSubExpr();
1342
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001343 // C++0x allows nullptr, and there's no further checking to be done for that.
1344 if (Arg->getType()->isNullPtrType())
1345 return false;
1346
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001347 // C++ [temp.arg.nontype]p1:
1348 //
1349 // A template-argument for a non-type, non-template
1350 // template-parameter shall be one of: [...]
1351 //
1352 // -- a pointer to member expressed as described in 5.3.1.
1353 QualifiedDeclRefExpr *DRE = 0;
1354
1355 // Ignore (and complain about) any excess parentheses.
1356 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
1357 if (!Invalid) {
1358 Diag(Arg->getSourceRange().getBegin(),
1359 diag::err_template_arg_extra_parens)
1360 << Arg->getSourceRange();
1361 Invalid = true;
1362 }
1363
1364 Arg = Parens->getSubExpr();
1365 }
1366
1367 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg))
1368 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
1369 DRE = dyn_cast<QualifiedDeclRefExpr>(UnOp->getSubExpr());
1370
1371 if (!DRE)
1372 return Diag(Arg->getSourceRange().getBegin(),
1373 diag::err_template_arg_not_pointer_to_member_form)
1374 << Arg->getSourceRange();
1375
1376 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
1377 assert((isa<FieldDecl>(DRE->getDecl()) ||
1378 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
1379 "Only non-static member pointers can make it here");
1380
1381 // Okay: this is the address of a non-static member, and therefore
1382 // a member pointer constant.
Douglas Gregorad964b32009-02-17 01:05:43 +00001383 Member = DRE->getDecl();
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001384 return Invalid;
1385 }
1386
1387 // We found something else, but we don't know specifically what it is.
1388 Diag(Arg->getSourceRange().getBegin(),
1389 diag::err_template_arg_not_pointer_to_member_form)
1390 << Arg->getSourceRange();
1391 Diag(DRE->getDecl()->getLocation(),
1392 diag::note_template_arg_refers_here);
1393 return true;
1394}
1395
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001396/// \brief Check a template argument against its corresponding
1397/// non-type template parameter.
1398///
Douglas Gregored3a3982009-03-03 04:44:36 +00001399/// This routine implements the semantics of C++ [temp.arg.nontype].
1400/// It returns true if an error occurred, and false otherwise. \p
1401/// InstantiatedParamType is the type of the non-type template
1402/// parameter after it has been instantiated.
Douglas Gregorad964b32009-02-17 01:05:43 +00001403///
1404/// If Converted is non-NULL and no errors occur, the value
1405/// of this argument will be added to the end of the Converted vector.
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001406bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Douglas Gregored3a3982009-03-03 04:44:36 +00001407 QualType InstantiatedParamType, Expr *&Arg,
Anders Carlssona35faf92009-06-05 03:43:12 +00001408 TemplateArgumentListBuilder *Converted) {
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001409 SourceLocation StartLoc = Arg->getSourceRange().getBegin();
1410
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001411 // If either the parameter has a dependent type or the argument is
1412 // type-dependent, there's nothing we can check now.
Douglas Gregorad964b32009-02-17 01:05:43 +00001413 // FIXME: Add template argument to Converted!
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001414 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
1415 // FIXME: Produce a cloned, canonical expression?
Anders Carlsson0297caf2009-06-11 16:06:49 +00001416 if (Converted)
1417 Converted->push_back(TemplateArgument(Arg));
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001418 return false;
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001419 }
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001420
1421 // C++ [temp.arg.nontype]p5:
1422 // The following conversions are performed on each expression used
1423 // as a non-type template-argument. If a non-type
1424 // template-argument cannot be converted to the type of the
1425 // corresponding template-parameter then the program is
1426 // ill-formed.
1427 //
1428 // -- for a non-type template-parameter of integral or
1429 // enumeration type, integral promotions (4.5) and integral
1430 // conversions (4.7) are applied.
Douglas Gregored3a3982009-03-03 04:44:36 +00001431 QualType ParamType = InstantiatedParamType;
Douglas Gregor2eedd992009-02-11 00:19:33 +00001432 QualType ArgType = Arg->getType();
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001433 if (ParamType->isIntegralType() || ParamType->isEnumeralType()) {
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001434 // C++ [temp.arg.nontype]p1:
1435 // A template-argument for a non-type, non-template
1436 // template-parameter shall be one of:
1437 //
1438 // -- an integral constant-expression of integral or enumeration
1439 // type; or
1440 // -- the name of a non-type template-parameter; or
1441 SourceLocation NonConstantLoc;
Douglas Gregorad964b32009-02-17 01:05:43 +00001442 llvm::APSInt Value;
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001443 if (!ArgType->isIntegralType() && !ArgType->isEnumeralType()) {
1444 Diag(Arg->getSourceRange().getBegin(),
1445 diag::err_template_arg_not_integral_or_enumeral)
1446 << ArgType << Arg->getSourceRange();
1447 Diag(Param->getLocation(), diag::note_template_param_here);
1448 return true;
1449 } else if (!Arg->isValueDependent() &&
Douglas Gregorad964b32009-02-17 01:05:43 +00001450 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001451 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
1452 << ArgType << Arg->getSourceRange();
1453 return true;
1454 }
1455
1456 // FIXME: We need some way to more easily get the unqualified form
1457 // of the types without going all the way to the
1458 // canonical type.
1459 if (Context.getCanonicalType(ParamType).getCVRQualifiers())
1460 ParamType = Context.getCanonicalType(ParamType).getUnqualifiedType();
1461 if (Context.getCanonicalType(ArgType).getCVRQualifiers())
1462 ArgType = Context.getCanonicalType(ArgType).getUnqualifiedType();
1463
1464 // Try to convert the argument to the parameter's type.
1465 if (ParamType == ArgType) {
1466 // Okay: no conversion necessary
1467 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
1468 !ParamType->isEnumeralType()) {
1469 // This is an integral promotion or conversion.
1470 ImpCastExprToType(Arg, ParamType);
1471 } else {
1472 // We can't perform this conversion.
1473 Diag(Arg->getSourceRange().getBegin(),
1474 diag::err_template_arg_not_convertible)
Douglas Gregored3a3982009-03-03 04:44:36 +00001475 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001476 Diag(Param->getLocation(), diag::note_template_param_here);
1477 return true;
1478 }
1479
Douglas Gregorafc86942009-03-14 00:20:21 +00001480 QualType IntegerType = Context.getCanonicalType(ParamType);
1481 if (const EnumType *Enum = IntegerType->getAsEnumType())
1482 IntegerType = Enum->getDecl()->getIntegerType();
1483
1484 if (!Arg->isValueDependent()) {
1485 // Check that an unsigned parameter does not receive a negative
1486 // value.
1487 if (IntegerType->isUnsignedIntegerType()
1488 && (Value.isSigned() && Value.isNegative())) {
1489 Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_negative)
1490 << Value.toString(10) << Param->getType()
1491 << Arg->getSourceRange();
1492 Diag(Param->getLocation(), diag::note_template_param_here);
1493 return true;
1494 }
1495
1496 // Check that we don't overflow the template parameter type.
1497 unsigned AllowedBits = Context.getTypeSize(IntegerType);
1498 if (Value.getActiveBits() > AllowedBits) {
1499 Diag(Arg->getSourceRange().getBegin(),
1500 diag::err_template_arg_too_large)
1501 << Value.toString(10) << Param->getType()
1502 << Arg->getSourceRange();
1503 Diag(Param->getLocation(), diag::note_template_param_here);
1504 return true;
1505 }
1506
1507 if (Value.getBitWidth() != AllowedBits)
1508 Value.extOrTrunc(AllowedBits);
1509 Value.setIsSigned(IntegerType->isSignedIntegerType());
1510 }
Douglas Gregorad964b32009-02-17 01:05:43 +00001511
1512 if (Converted) {
1513 // Add the value of this argument to the list of converted
1514 // arguments. We use the bitwidth and signedness of the template
1515 // parameter.
Douglas Gregor396f1142009-03-13 21:01:28 +00001516 if (Arg->isValueDependent()) {
1517 // The argument is value-dependent. Create a new
1518 // TemplateArgument with the converted expression.
1519 Converted->push_back(TemplateArgument(Arg));
1520 return false;
1521 }
1522
Douglas Gregor544cda62009-03-14 00:03:48 +00001523 Converted->push_back(TemplateArgument(StartLoc, Value,
Sebastian Redl9f1a3df2009-05-27 19:21:29 +00001524 ParamType->isEnumeralType() ? ParamType : IntegerType));
Douglas Gregorad964b32009-02-17 01:05:43 +00001525 }
1526
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001527 return false;
1528 }
Douglas Gregor2eedd992009-02-11 00:19:33 +00001529
Douglas Gregor3f411962009-02-11 01:18:59 +00001530 // Handle pointer-to-function, reference-to-function, and
1531 // pointer-to-member-function all in (roughly) the same way.
1532 if (// -- For a non-type template-parameter of type pointer to
1533 // function, only the function-to-pointer conversion (4.3) is
1534 // applied. If the template-argument represents a set of
1535 // overloaded functions (or a pointer to such), the matching
1536 // function is selected from the set (13.4).
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001537 // In C++0x, any std::nullptr_t value can be converted.
Douglas Gregor3f411962009-02-11 01:18:59 +00001538 (ParamType->isPointerType() &&
1539 ParamType->getAsPointerType()->getPointeeType()->isFunctionType()) ||
1540 // -- For a non-type template-parameter of type reference to
1541 // function, no conversions apply. If the template-argument
1542 // represents a set of overloaded functions, the matching
1543 // function is selected from the set (13.4).
1544 (ParamType->isReferenceType() &&
1545 ParamType->getAsReferenceType()->getPointeeType()->isFunctionType()) ||
1546 // -- For a non-type template-parameter of type pointer to
1547 // member function, no conversions apply. If the
1548 // template-argument represents a set of overloaded member
1549 // functions, the matching member function is selected from
1550 // the set (13.4).
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001551 // Again, C++0x allows a std::nullptr_t value.
Douglas Gregor3f411962009-02-11 01:18:59 +00001552 (ParamType->isMemberPointerType() &&
1553 ParamType->getAsMemberPointerType()->getPointeeType()
1554 ->isFunctionType())) {
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001555 if (Context.hasSameUnqualifiedType(ArgType,
1556 ParamType.getNonReferenceType())) {
Douglas Gregor2eedd992009-02-11 00:19:33 +00001557 // We don't have to do anything: the types already match.
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001558 } else if (ArgType->isNullPtrType() && (ParamType->isPointerType() ||
1559 ParamType->isMemberPointerType())) {
1560 ArgType = ParamType;
1561 ImpCastExprToType(Arg, ParamType);
Douglas Gregor3f411962009-02-11 01:18:59 +00001562 } else if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregor2eedd992009-02-11 00:19:33 +00001563 ArgType = Context.getPointerType(ArgType);
1564 ImpCastExprToType(Arg, ArgType);
1565 } else if (FunctionDecl *Fn
1566 = ResolveAddressOfOverloadedFunction(Arg, ParamType, true)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00001567 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
1568 return true;
1569
Douglas Gregor2eedd992009-02-11 00:19:33 +00001570 FixOverloadedFunctionReference(Arg, Fn);
1571 ArgType = Arg->getType();
Douglas Gregor3f411962009-02-11 01:18:59 +00001572 if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregor2eedd992009-02-11 00:19:33 +00001573 ArgType = Context.getPointerType(Arg->getType());
1574 ImpCastExprToType(Arg, ArgType);
1575 }
1576 }
1577
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001578 if (!Context.hasSameUnqualifiedType(ArgType,
1579 ParamType.getNonReferenceType())) {
Douglas Gregor2eedd992009-02-11 00:19:33 +00001580 // We can't perform this conversion.
1581 Diag(Arg->getSourceRange().getBegin(),
1582 diag::err_template_arg_not_convertible)
Douglas Gregored3a3982009-03-03 04:44:36 +00001583 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor2eedd992009-02-11 00:19:33 +00001584 Diag(Param->getLocation(), diag::note_template_param_here);
1585 return true;
1586 }
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001587
Douglas Gregorad964b32009-02-17 01:05:43 +00001588 if (ParamType->isMemberPointerType()) {
1589 NamedDecl *Member = 0;
1590 if (CheckTemplateArgumentPointerToMember(Arg, Member))
1591 return true;
1592
Douglas Gregor9054f982009-05-10 22:57:19 +00001593 if (Converted) {
Douglas Gregor8a7f1fa2009-05-10 23:27:08 +00001594 Member = cast_or_null<NamedDecl>(Context.getCanonicalDecl(Member));
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001595 Converted->push_back(TemplateArgument(StartLoc, Member));
Douglas Gregor9054f982009-05-10 22:57:19 +00001596 }
Douglas Gregorad964b32009-02-17 01:05:43 +00001597
1598 return false;
1599 }
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001600
Douglas Gregorad964b32009-02-17 01:05:43 +00001601 NamedDecl *Entity = 0;
1602 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1603 return true;
1604
Douglas Gregor9054f982009-05-10 22:57:19 +00001605 if (Converted) {
Douglas Gregor8a7f1fa2009-05-10 23:27:08 +00001606 Entity = cast_or_null<NamedDecl>(Context.getCanonicalDecl(Entity));
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001607 Converted->push_back(TemplateArgument(StartLoc, Entity));
Douglas Gregor9054f982009-05-10 22:57:19 +00001608 }
Douglas Gregorad964b32009-02-17 01:05:43 +00001609 return false;
Douglas Gregor2eedd992009-02-11 00:19:33 +00001610 }
1611
Chris Lattner320dff22009-02-20 21:37:53 +00001612 if (ParamType->isPointerType()) {
Douglas Gregor3f411962009-02-11 01:18:59 +00001613 // -- for a non-type template-parameter of type pointer to
1614 // object, qualification conversions (4.4) and the
1615 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001616 // C++0x also allows a value of std::nullptr_t.
Douglas Gregor26ea1222009-03-24 20:32:41 +00001617 assert(ParamType->getAsPointerType()->getPointeeType()->isObjectType() &&
Douglas Gregor3f411962009-02-11 01:18:59 +00001618 "Only object pointers allowed here");
Douglas Gregord8c8c092009-02-11 00:44:29 +00001619
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001620 if (ArgType->isNullPtrType()) {
1621 ArgType = ParamType;
1622 ImpCastExprToType(Arg, ParamType);
1623 } else if (ArgType->isArrayType()) {
Douglas Gregor3f411962009-02-11 01:18:59 +00001624 ArgType = Context.getArrayDecayedType(ArgType);
1625 ImpCastExprToType(Arg, ArgType);
Douglas Gregord8c8c092009-02-11 00:44:29 +00001626 }
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001627
Douglas Gregor3f411962009-02-11 01:18:59 +00001628 if (IsQualificationConversion(ArgType, ParamType)) {
1629 ArgType = ParamType;
1630 ImpCastExprToType(Arg, ParamType);
1631 }
1632
Douglas Gregor0ea4e302009-02-11 18:22:40 +00001633 if (!Context.hasSameUnqualifiedType(ArgType, ParamType)) {
Douglas Gregor3f411962009-02-11 01:18:59 +00001634 // We can't perform this conversion.
1635 Diag(Arg->getSourceRange().getBegin(),
1636 diag::err_template_arg_not_convertible)
Douglas Gregored3a3982009-03-03 04:44:36 +00001637 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor3f411962009-02-11 01:18:59 +00001638 Diag(Param->getLocation(), diag::note_template_param_here);
1639 return true;
1640 }
1641
Douglas Gregorad964b32009-02-17 01:05:43 +00001642 NamedDecl *Entity = 0;
1643 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1644 return true;
1645
Douglas Gregor9054f982009-05-10 22:57:19 +00001646 if (Converted) {
Douglas Gregor8a7f1fa2009-05-10 23:27:08 +00001647 Entity = cast_or_null<NamedDecl>(Context.getCanonicalDecl(Entity));
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001648 Converted->push_back(TemplateArgument(StartLoc, Entity));
Douglas Gregor9054f982009-05-10 22:57:19 +00001649 }
Douglas Gregorad964b32009-02-17 01:05:43 +00001650
1651 return false;
Douglas Gregord8c8c092009-02-11 00:44:29 +00001652 }
Douglas Gregor3f411962009-02-11 01:18:59 +00001653
1654 if (const ReferenceType *ParamRefType = ParamType->getAsReferenceType()) {
1655 // -- For a non-type template-parameter of type reference to
1656 // object, no conversions apply. The type referred to by the
1657 // reference may be more cv-qualified than the (otherwise
1658 // identical) type of the template-argument. The
1659 // template-parameter is bound directly to the
1660 // template-argument, which must be an lvalue.
Douglas Gregor26ea1222009-03-24 20:32:41 +00001661 assert(ParamRefType->getPointeeType()->isObjectType() &&
Douglas Gregor3f411962009-02-11 01:18:59 +00001662 "Only object references allowed here");
Douglas Gregord8c8c092009-02-11 00:44:29 +00001663
Douglas Gregor0ea4e302009-02-11 18:22:40 +00001664 if (!Context.hasSameUnqualifiedType(ParamRefType->getPointeeType(), ArgType)) {
Douglas Gregor3f411962009-02-11 01:18:59 +00001665 Diag(Arg->getSourceRange().getBegin(),
1666 diag::err_template_arg_no_ref_bind)
Douglas Gregored3a3982009-03-03 04:44:36 +00001667 << InstantiatedParamType << Arg->getType()
Douglas Gregor3f411962009-02-11 01:18:59 +00001668 << Arg->getSourceRange();
1669 Diag(Param->getLocation(), diag::note_template_param_here);
1670 return true;
1671 }
1672
1673 unsigned ParamQuals
1674 = Context.getCanonicalType(ParamType).getCVRQualifiers();
1675 unsigned ArgQuals = Context.getCanonicalType(ArgType).getCVRQualifiers();
1676
1677 if ((ParamQuals | ArgQuals) != ParamQuals) {
1678 Diag(Arg->getSourceRange().getBegin(),
1679 diag::err_template_arg_ref_bind_ignores_quals)
Douglas Gregored3a3982009-03-03 04:44:36 +00001680 << InstantiatedParamType << Arg->getType()
Douglas Gregor3f411962009-02-11 01:18:59 +00001681 << Arg->getSourceRange();
1682 Diag(Param->getLocation(), diag::note_template_param_here);
1683 return true;
1684 }
1685
Douglas Gregorad964b32009-02-17 01:05:43 +00001686 NamedDecl *Entity = 0;
1687 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1688 return true;
1689
Douglas Gregor9054f982009-05-10 22:57:19 +00001690 if (Converted) {
1691 Entity = cast<NamedDecl>(Context.getCanonicalDecl(Entity));
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001692 Converted->push_back(TemplateArgument(StartLoc, Entity));
Douglas Gregor9054f982009-05-10 22:57:19 +00001693 }
Douglas Gregorad964b32009-02-17 01:05:43 +00001694
1695 return false;
Douglas Gregor3f411962009-02-11 01:18:59 +00001696 }
Douglas Gregor3628e1b2009-02-11 16:16:59 +00001697
1698 // -- For a non-type template-parameter of type pointer to data
1699 // member, qualification conversions (4.4) are applied.
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001700 // C++0x allows std::nullptr_t values.
Douglas Gregor3628e1b2009-02-11 16:16:59 +00001701 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
1702
Douglas Gregor0ea4e302009-02-11 18:22:40 +00001703 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
Douglas Gregor3628e1b2009-02-11 16:16:59 +00001704 // Types match exactly: nothing more to do here.
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001705 } else if (ArgType->isNullPtrType()) {
1706 ImpCastExprToType(Arg, ParamType);
Douglas Gregor3628e1b2009-02-11 16:16:59 +00001707 } else if (IsQualificationConversion(ArgType, ParamType)) {
1708 ImpCastExprToType(Arg, ParamType);
1709 } else {
1710 // We can't perform this conversion.
1711 Diag(Arg->getSourceRange().getBegin(),
1712 diag::err_template_arg_not_convertible)
Douglas Gregored3a3982009-03-03 04:44:36 +00001713 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor3628e1b2009-02-11 16:16:59 +00001714 Diag(Param->getLocation(), diag::note_template_param_here);
1715 return true;
1716 }
1717
Douglas Gregorad964b32009-02-17 01:05:43 +00001718 NamedDecl *Member = 0;
1719 if (CheckTemplateArgumentPointerToMember(Arg, Member))
1720 return true;
1721
Douglas Gregor9054f982009-05-10 22:57:19 +00001722 if (Converted) {
Douglas Gregor8a7f1fa2009-05-10 23:27:08 +00001723 Member = cast_or_null<NamedDecl>(Context.getCanonicalDecl(Member));
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001724 Converted->push_back(TemplateArgument(StartLoc, Member));
Douglas Gregor9054f982009-05-10 22:57:19 +00001725 }
1726
Douglas Gregorad964b32009-02-17 01:05:43 +00001727 return false;
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001728}
1729
1730/// \brief Check a template argument against its corresponding
1731/// template template parameter.
1732///
1733/// This routine implements the semantics of C++ [temp.arg.template].
1734/// It returns true if an error occurred, and false otherwise.
1735bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
1736 DeclRefExpr *Arg) {
Douglas Gregore8e367f2009-02-10 00:24:35 +00001737 assert(isa<TemplateDecl>(Arg->getDecl()) && "Only template decls allowed");
1738 TemplateDecl *Template = cast<TemplateDecl>(Arg->getDecl());
1739
1740 // C++ [temp.arg.template]p1:
1741 // A template-argument for a template template-parameter shall be
1742 // the name of a class template, expressed as id-expression. Only
1743 // primary class templates are considered when matching the
1744 // template template argument with the corresponding parameter;
1745 // partial specializations are not considered even if their
1746 // parameter lists match that of the template template parameter.
1747 if (!isa<ClassTemplateDecl>(Template)) {
1748 assert(isa<FunctionTemplateDecl>(Template) &&
1749 "Only function templates are possible here");
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001750 Diag(Arg->getSourceRange().getBegin(),
1751 diag::note_template_arg_refers_here_func)
Douglas Gregore8e367f2009-02-10 00:24:35 +00001752 << Template;
1753 }
1754
1755 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
1756 Param->getTemplateParameters(),
1757 true, true,
1758 Arg->getSourceRange().getBegin());
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001759}
1760
Douglas Gregord406b032009-02-06 22:42:48 +00001761/// \brief Determine whether the given template parameter lists are
1762/// equivalent.
1763///
1764/// \param New The new template parameter list, typically written in the
1765/// source code as part of a new template declaration.
1766///
1767/// \param Old The old template parameter list, typically found via
1768/// name lookup of the template declared with this template parameter
1769/// list.
1770///
1771/// \param Complain If true, this routine will produce a diagnostic if
1772/// the template parameter lists are not equivalent.
1773///
Douglas Gregore8e367f2009-02-10 00:24:35 +00001774/// \param IsTemplateTemplateParm If true, this routine is being
1775/// called to compare the template parameter lists of a template
1776/// template parameter.
1777///
1778/// \param TemplateArgLoc If this source location is valid, then we
1779/// are actually checking the template parameter list of a template
1780/// argument (New) against the template parameter list of its
1781/// corresponding template template parameter (Old). We produce
1782/// slightly different diagnostics in this scenario.
1783///
Douglas Gregord406b032009-02-06 22:42:48 +00001784/// \returns True if the template parameter lists are equal, false
1785/// otherwise.
1786bool
1787Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
1788 TemplateParameterList *Old,
1789 bool Complain,
Douglas Gregore8e367f2009-02-10 00:24:35 +00001790 bool IsTemplateTemplateParm,
1791 SourceLocation TemplateArgLoc) {
Douglas Gregord406b032009-02-06 22:42:48 +00001792 if (Old->size() != New->size()) {
1793 if (Complain) {
Douglas Gregore8e367f2009-02-10 00:24:35 +00001794 unsigned NextDiag = diag::err_template_param_list_different_arity;
1795 if (TemplateArgLoc.isValid()) {
1796 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
1797 NextDiag = diag::note_template_param_list_different_arity;
1798 }
1799 Diag(New->getTemplateLoc(), NextDiag)
1800 << (New->size() > Old->size())
1801 << IsTemplateTemplateParm
1802 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
Douglas Gregord406b032009-02-06 22:42:48 +00001803 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
1804 << IsTemplateTemplateParm
1805 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
1806 }
1807
1808 return false;
1809 }
1810
1811 for (TemplateParameterList::iterator OldParm = Old->begin(),
1812 OldParmEnd = Old->end(), NewParm = New->begin();
1813 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
1814 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
Douglas Gregore8e367f2009-02-10 00:24:35 +00001815 unsigned NextDiag = diag::err_template_param_different_kind;
1816 if (TemplateArgLoc.isValid()) {
1817 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
1818 NextDiag = diag::note_template_param_different_kind;
1819 }
1820 Diag((*NewParm)->getLocation(), NextDiag)
Douglas Gregord406b032009-02-06 22:42:48 +00001821 << IsTemplateTemplateParm;
1822 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
1823 << IsTemplateTemplateParm;
1824 return false;
1825 }
1826
1827 if (isa<TemplateTypeParmDecl>(*OldParm)) {
1828 // Okay; all template type parameters are equivalent (since we
Douglas Gregore8e367f2009-02-10 00:24:35 +00001829 // know we're at the same index).
1830#if 0
Mike Stumpe127ae32009-05-16 07:39:55 +00001831 // FIXME: Enable this code in debug mode *after* we properly go through
1832 // and "instantiate" the template parameter lists of template template
1833 // parameters. It's only after this instantiation that (1) any dependent
1834 // types within the template parameter list of the template template
1835 // parameter can be checked, and (2) the template type parameter depths
Douglas Gregore8e367f2009-02-10 00:24:35 +00001836 // will match up.
Douglas Gregord406b032009-02-06 22:42:48 +00001837 QualType OldParmType
1838 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*OldParm));
1839 QualType NewParmType
1840 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*NewParm));
1841 assert(Context.getCanonicalType(OldParmType) ==
1842 Context.getCanonicalType(NewParmType) &&
1843 "type parameter mismatch?");
1844#endif
1845 } else if (NonTypeTemplateParmDecl *OldNTTP
1846 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
1847 // The types of non-type template parameters must agree.
1848 NonTypeTemplateParmDecl *NewNTTP
1849 = cast<NonTypeTemplateParmDecl>(*NewParm);
1850 if (Context.getCanonicalType(OldNTTP->getType()) !=
1851 Context.getCanonicalType(NewNTTP->getType())) {
1852 if (Complain) {
Douglas Gregore8e367f2009-02-10 00:24:35 +00001853 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
1854 if (TemplateArgLoc.isValid()) {
1855 Diag(TemplateArgLoc,
1856 diag::err_template_arg_template_params_mismatch);
1857 NextDiag = diag::note_template_nontype_parm_different_type;
1858 }
1859 Diag(NewNTTP->getLocation(), NextDiag)
Douglas Gregord406b032009-02-06 22:42:48 +00001860 << NewNTTP->getType()
1861 << IsTemplateTemplateParm;
1862 Diag(OldNTTP->getLocation(),
1863 diag::note_template_nontype_parm_prev_declaration)
1864 << OldNTTP->getType();
1865 }
1866 return false;
1867 }
1868 } else {
1869 // The template parameter lists of template template
1870 // parameters must agree.
1871 // FIXME: Could we perform a faster "type" comparison here?
1872 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
1873 "Only template template parameters handled here");
1874 TemplateTemplateParmDecl *OldTTP
1875 = cast<TemplateTemplateParmDecl>(*OldParm);
1876 TemplateTemplateParmDecl *NewTTP
1877 = cast<TemplateTemplateParmDecl>(*NewParm);
1878 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
1879 OldTTP->getTemplateParameters(),
1880 Complain,
Douglas Gregore8e367f2009-02-10 00:24:35 +00001881 /*IsTemplateTemplateParm=*/true,
1882 TemplateArgLoc))
Douglas Gregord406b032009-02-06 22:42:48 +00001883 return false;
1884 }
1885 }
1886
1887 return true;
1888}
1889
1890/// \brief Check whether a template can be declared within this scope.
1891///
1892/// If the template declaration is valid in this scope, returns
1893/// false. Otherwise, issues a diagnostic and returns true.
1894bool
1895Sema::CheckTemplateDeclScope(Scope *S,
1896 MultiTemplateParamsArg &TemplateParameterLists) {
1897 assert(TemplateParameterLists.size() > 0 && "Not a template");
1898
1899 // Find the nearest enclosing declaration scope.
1900 while ((S->getFlags() & Scope::DeclScope) == 0 ||
1901 (S->getFlags() & Scope::TemplateParamScope) != 0)
1902 S = S->getParent();
1903
1904 TemplateParameterList *TemplateParams =
1905 static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
1906 SourceLocation TemplateLoc = TemplateParams->getTemplateLoc();
1907 SourceRange TemplateRange
1908 = SourceRange(TemplateLoc, TemplateParams->getRAngleLoc());
1909
1910 // C++ [temp]p2:
1911 // A template-declaration can appear only as a namespace scope or
1912 // class scope declaration.
1913 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
1914 while (Ctx && isa<LinkageSpecDecl>(Ctx)) {
1915 if (cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
1916 return Diag(TemplateLoc, diag::err_template_linkage)
1917 << TemplateRange;
1918
1919 Ctx = Ctx->getParent();
1920 }
1921
1922 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
1923 return false;
1924
1925 return Diag(TemplateLoc, diag::err_template_outside_namespace_or_class_scope)
1926 << TemplateRange;
1927}
Douglas Gregora08b6c72009-02-17 23:15:12 +00001928
Douglas Gregor90177912009-05-13 18:28:20 +00001929/// \brief Check whether a class template specialization or explicit
1930/// instantiation in the current context is well-formed.
Douglas Gregor0d93f692009-02-25 22:02:03 +00001931///
Douglas Gregor90177912009-05-13 18:28:20 +00001932/// This routine determines whether a class template specialization or
1933/// explicit instantiation can be declared in the current context
1934/// (C++ [temp.expl.spec]p2, C++0x [temp.explicit]p2) and emits
1935/// appropriate diagnostics if there was an error. It returns true if
1936// there was an error that we cannot recover from, and false otherwise.
Douglas Gregor0d93f692009-02-25 22:02:03 +00001937bool
1938Sema::CheckClassTemplateSpecializationScope(ClassTemplateDecl *ClassTemplate,
1939 ClassTemplateSpecializationDecl *PrevDecl,
1940 SourceLocation TemplateNameLoc,
Douglas Gregor90177912009-05-13 18:28:20 +00001941 SourceRange ScopeSpecifierRange,
1942 bool ExplicitInstantiation) {
Douglas Gregor0d93f692009-02-25 22:02:03 +00001943 // C++ [temp.expl.spec]p2:
1944 // An explicit specialization shall be declared in the namespace
1945 // of which the template is a member, or, for member templates, in
1946 // the namespace of which the enclosing class or enclosing class
1947 // template is a member. An explicit specialization of a member
1948 // function, member class or static data member of a class
1949 // template shall be declared in the namespace of which the class
1950 // template is a member. Such a declaration may also be a
1951 // definition. If the declaration is not a definition, the
1952 // specialization may be defined later in the name- space in which
1953 // the explicit specialization was declared, or in a namespace
1954 // that encloses the one in which the explicit specialization was
1955 // declared.
1956 if (CurContext->getLookupContext()->isFunctionOrMethod()) {
1957 Diag(TemplateNameLoc, diag::err_template_spec_decl_function_scope)
Douglas Gregor90177912009-05-13 18:28:20 +00001958 << ExplicitInstantiation << ClassTemplate;
Douglas Gregor0d93f692009-02-25 22:02:03 +00001959 return true;
1960 }
1961
1962 DeclContext *DC = CurContext->getEnclosingNamespaceContext();
1963 DeclContext *TemplateContext
1964 = ClassTemplate->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregor90177912009-05-13 18:28:20 +00001965 if ((!PrevDecl || PrevDecl->getSpecializationKind() == TSK_Undeclared) &&
1966 !ExplicitInstantiation) {
Douglas Gregor0d93f692009-02-25 22:02:03 +00001967 // There is no prior declaration of this entity, so this
1968 // specialization must be in the same context as the template
1969 // itself.
1970 if (DC != TemplateContext) {
1971 if (isa<TranslationUnitDecl>(TemplateContext))
1972 Diag(TemplateNameLoc, diag::err_template_spec_decl_out_of_scope_global)
1973 << ClassTemplate << ScopeSpecifierRange;
1974 else if (isa<NamespaceDecl>(TemplateContext))
1975 Diag(TemplateNameLoc, diag::err_template_spec_decl_out_of_scope)
1976 << ClassTemplate << cast<NamedDecl>(TemplateContext)
1977 << ScopeSpecifierRange;
1978
1979 Diag(ClassTemplate->getLocation(), diag::note_template_decl_here);
1980 }
1981
1982 return false;
1983 }
1984
1985 // We have a previous declaration of this entity. Make sure that
1986 // this redeclaration (or definition) occurs in an enclosing namespace.
1987 if (!CurContext->Encloses(TemplateContext)) {
Mike Stumpe127ae32009-05-16 07:39:55 +00001988 // FIXME: In C++98, we would like to turn these errors into warnings,
1989 // dependent on a -Wc++0x flag.
Douglas Gregor90177912009-05-13 18:28:20 +00001990 bool SuppressedDiag = false;
1991 if (isa<TranslationUnitDecl>(TemplateContext)) {
1992 if (!ExplicitInstantiation || getLangOptions().CPlusPlus0x)
1993 Diag(TemplateNameLoc, diag::err_template_spec_redecl_global_scope)
1994 << ExplicitInstantiation << ClassTemplate << ScopeSpecifierRange;
1995 else
1996 SuppressedDiag = true;
1997 } else if (isa<NamespaceDecl>(TemplateContext)) {
1998 if (!ExplicitInstantiation || getLangOptions().CPlusPlus0x)
1999 Diag(TemplateNameLoc, diag::err_template_spec_redecl_out_of_scope)
2000 << ExplicitInstantiation << ClassTemplate
2001 << cast<NamedDecl>(TemplateContext) << ScopeSpecifierRange;
2002 else
2003 SuppressedDiag = true;
2004 }
Douglas Gregor0d93f692009-02-25 22:02:03 +00002005
Douglas Gregor90177912009-05-13 18:28:20 +00002006 if (!SuppressedDiag)
2007 Diag(ClassTemplate->getLocation(), diag::note_template_decl_here);
Douglas Gregor0d93f692009-02-25 22:02:03 +00002008 }
2009
2010 return false;
2011}
2012
Douglas Gregorc5d6fa72009-03-25 00:13:59 +00002013Sema::DeclResult
Douglas Gregora08b6c72009-02-17 23:15:12 +00002014Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec, TagKind TK,
2015 SourceLocation KWLoc,
2016 const CXXScopeSpec &SS,
Douglas Gregordd13e842009-03-30 22:58:21 +00002017 TemplateTy TemplateD,
Douglas Gregora08b6c72009-02-17 23:15:12 +00002018 SourceLocation TemplateNameLoc,
2019 SourceLocation LAngleLoc,
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00002020 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregora08b6c72009-02-17 23:15:12 +00002021 SourceLocation *TemplateArgLocs,
2022 SourceLocation RAngleLoc,
2023 AttributeList *Attr,
2024 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregora08b6c72009-02-17 23:15:12 +00002025 // Find the class template we're specializing
Douglas Gregordd13e842009-03-30 22:58:21 +00002026 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Douglas Gregora08b6c72009-02-17 23:15:12 +00002027 ClassTemplateDecl *ClassTemplate
Douglas Gregordd13e842009-03-30 22:58:21 +00002028 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
Douglas Gregora08b6c72009-02-17 23:15:12 +00002029
Douglas Gregor58944ac2009-05-31 09:31:02 +00002030 bool isPartialSpecialization = false;
2031
Douglas Gregor0d93f692009-02-25 22:02:03 +00002032 // Check the validity of the template headers that introduce this
2033 // template.
Douglas Gregor50113ca2009-02-25 22:18:32 +00002034 // FIXME: Once we have member templates, we'll need to check
2035 // C++ [temp.expl.spec]p17-18, where we could have multiple levels of
2036 // template<> headers.
Douglas Gregor3bb30002009-02-26 21:00:50 +00002037 if (TemplateParameterLists.size() == 0)
2038 Diag(KWLoc, diag::err_template_spec_needs_header)
Douglas Gregor61be3602009-02-27 17:53:17 +00002039 << CodeModificationHint::CreateInsertion(KWLoc, "template<> ");
Douglas Gregor3bb30002009-02-26 21:00:50 +00002040 else {
Douglas Gregor0d93f692009-02-25 22:02:03 +00002041 TemplateParameterList *TemplateParams
2042 = static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
Chris Lattner5261d0c2009-03-28 19:18:32 +00002043 if (TemplateParameterLists.size() > 1) {
2044 Diag(TemplateParams->getTemplateLoc(),
2045 diag::err_template_spec_extra_headers);
2046 return true;
2047 }
Douglas Gregor0d93f692009-02-25 22:02:03 +00002048
Douglas Gregor58944ac2009-05-31 09:31:02 +00002049 // FIXME: We'll need more checks, here!
2050 if (TemplateParams->size() > 0)
2051 isPartialSpecialization = true;
Douglas Gregor0d93f692009-02-25 22:02:03 +00002052 }
2053
Douglas Gregora08b6c72009-02-17 23:15:12 +00002054 // Check that the specialization uses the same tag kind as the
2055 // original template.
2056 TagDecl::TagKind Kind;
2057 switch (TagSpec) {
2058 default: assert(0 && "Unknown tag type!");
2059 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2060 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2061 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2062 }
Douglas Gregor625185c2009-05-14 16:41:31 +00002063 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
2064 Kind, KWLoc,
2065 *ClassTemplate->getIdentifier())) {
Douglas Gregor3faaa812009-04-01 23:51:29 +00002066 Diag(KWLoc, diag::err_use_with_wrong_tag)
2067 << ClassTemplate
2068 << CodeModificationHint::CreateReplacement(KWLoc,
2069 ClassTemplate->getTemplatedDecl()->getKindName());
Douglas Gregora08b6c72009-02-17 23:15:12 +00002070 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
2071 diag::note_previous_use);
2072 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
2073 }
2074
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00002075 // Translate the parser's template argument list in our AST format.
2076 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
2077 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
2078
Douglas Gregora08b6c72009-02-17 23:15:12 +00002079 // Check that the template argument list is well-formed for this
2080 // template.
Anders Carlsson558a3a32009-06-05 05:31:27 +00002081 TemplateArgumentListBuilder ConvertedTemplateArgs(Context);
Douglas Gregora08b6c72009-02-17 23:15:12 +00002082 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00002083 &TemplateArgs[0], TemplateArgs.size(),
2084 RAngleLoc, ConvertedTemplateArgs))
Douglas Gregorc5d6fa72009-03-25 00:13:59 +00002085 return true;
Douglas Gregora08b6c72009-02-17 23:15:12 +00002086
2087 assert((ConvertedTemplateArgs.size() ==
2088 ClassTemplate->getTemplateParameters()->size()) &&
2089 "Converted template argument list is too short!");
2090
Douglas Gregor58944ac2009-05-31 09:31:02 +00002091 // Find the class template (partial) specialization declaration that
Douglas Gregora08b6c72009-02-17 23:15:12 +00002092 // corresponds to these arguments.
2093 llvm::FoldingSetNodeID ID;
Douglas Gregor58944ac2009-05-31 09:31:02 +00002094 if (isPartialSpecialization)
2095 // FIXME: Template parameter list matters, too
Anders Carlssona35faf92009-06-05 03:43:12 +00002096 ClassTemplatePartialSpecializationDecl::Profile(ID,
2097 ConvertedTemplateArgs.getFlatArgumentList(),
2098 ConvertedTemplateArgs.flatSize());
Douglas Gregor58944ac2009-05-31 09:31:02 +00002099 else
Anders Carlssona35faf92009-06-05 03:43:12 +00002100 ClassTemplateSpecializationDecl::Profile(ID,
2101 ConvertedTemplateArgs.getFlatArgumentList(),
2102 ConvertedTemplateArgs.flatSize());
Douglas Gregora08b6c72009-02-17 23:15:12 +00002103 void *InsertPos = 0;
Douglas Gregor58944ac2009-05-31 09:31:02 +00002104 ClassTemplateSpecializationDecl *PrevDecl = 0;
2105
2106 if (isPartialSpecialization)
2107 PrevDecl
2108 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
2109 InsertPos);
2110 else
2111 PrevDecl
2112 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregora08b6c72009-02-17 23:15:12 +00002113
2114 ClassTemplateSpecializationDecl *Specialization = 0;
2115
Douglas Gregor0d93f692009-02-25 22:02:03 +00002116 // Check whether we can declare a class template specialization in
2117 // the current scope.
2118 if (CheckClassTemplateSpecializationScope(ClassTemplate, PrevDecl,
2119 TemplateNameLoc,
Douglas Gregor90177912009-05-13 18:28:20 +00002120 SS.getRange(),
2121 /*ExplicitInstantiation=*/false))
Douglas Gregorc5d6fa72009-03-25 00:13:59 +00002122 return true;
Douglas Gregor0d93f692009-02-25 22:02:03 +00002123
Douglas Gregora08b6c72009-02-17 23:15:12 +00002124 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
2125 // Since the only prior class template specialization with these
2126 // arguments was referenced but not declared, reuse that
2127 // declaration node as our own, updating its source location to
2128 // reflect our new declaration.
Douglas Gregora08b6c72009-02-17 23:15:12 +00002129 Specialization = PrevDecl;
Douglas Gregor50113ca2009-02-25 22:18:32 +00002130 Specialization->setLocation(TemplateNameLoc);
Douglas Gregora08b6c72009-02-17 23:15:12 +00002131 PrevDecl = 0;
Douglas Gregor58944ac2009-05-31 09:31:02 +00002132 } else if (isPartialSpecialization) {
2133 // FIXME: extra checking for partial specializations
2134
2135 // Create a new class template partial specialization declaration node.
2136 TemplateParameterList *TemplateParams
2137 = static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
2138 ClassTemplatePartialSpecializationDecl *PrevPartial
2139 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
2140 ClassTemplatePartialSpecializationDecl *Partial
2141 = ClassTemplatePartialSpecializationDecl::Create(Context,
2142 ClassTemplate->getDeclContext(),
Anders Carlsson6e9d02f2009-06-05 04:06:48 +00002143 TemplateNameLoc,
2144 TemplateParams,
2145 ClassTemplate,
2146 ConvertedTemplateArgs,
2147 PrevPartial);
Douglas Gregor58944ac2009-05-31 09:31:02 +00002148
2149 if (PrevPartial) {
2150 ClassTemplate->getPartialSpecializations().RemoveNode(PrevPartial);
2151 ClassTemplate->getPartialSpecializations().GetOrInsertNode(Partial);
2152 } else {
2153 ClassTemplate->getPartialSpecializations().InsertNode(Partial, InsertPos);
2154 }
2155 Specialization = Partial;
Douglas Gregora08b6c72009-02-17 23:15:12 +00002156 } else {
2157 // Create a new class template specialization declaration node for
2158 // this explicit specialization.
2159 Specialization
2160 = ClassTemplateSpecializationDecl::Create(Context,
2161 ClassTemplate->getDeclContext(),
2162 TemplateNameLoc,
Anders Carlsson6e9d02f2009-06-05 04:06:48 +00002163 ClassTemplate,
2164 ConvertedTemplateArgs,
Douglas Gregora08b6c72009-02-17 23:15:12 +00002165 PrevDecl);
2166
2167 if (PrevDecl) {
2168 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
2169 ClassTemplate->getSpecializations().GetOrInsertNode(Specialization);
2170 } else {
2171 ClassTemplate->getSpecializations().InsertNode(Specialization,
2172 InsertPos);
2173 }
2174 }
2175
2176 // Note that this is an explicit specialization.
2177 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
2178
2179 // Check that this isn't a redefinition of this specialization.
2180 if (TK == TK_Definition) {
2181 if (RecordDecl *Def = Specialization->getDefinition(Context)) {
Mike Stumpe127ae32009-05-16 07:39:55 +00002182 // FIXME: Should also handle explicit specialization after implicit
2183 // instantiation with a special diagnostic.
Douglas Gregora08b6c72009-02-17 23:15:12 +00002184 SourceRange Range(TemplateNameLoc, RAngleLoc);
2185 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregor58944ac2009-05-31 09:31:02 +00002186 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregora08b6c72009-02-17 23:15:12 +00002187 Diag(Def->getLocation(), diag::note_previous_definition);
2188 Specialization->setInvalidDecl();
Douglas Gregorc5d6fa72009-03-25 00:13:59 +00002189 return true;
Douglas Gregora08b6c72009-02-17 23:15:12 +00002190 }
2191 }
2192
Douglas Gregor9c7825b2009-02-26 22:19:44 +00002193 // Build the fully-sugared type for this class template
2194 // specialization as the user wrote in the specialization
2195 // itself. This means that we'll pretty-print the type retrieved
2196 // from the specialization's declaration the way that the user
2197 // actually wrote the specialization, rather than formatting the
2198 // name based on the "canonical" representation used to store the
2199 // template arguments in the specialization.
Douglas Gregor8c795a12009-03-19 00:39:20 +00002200 QualType WrittenTy
Douglas Gregordd13e842009-03-30 22:58:21 +00002201 = Context.getTemplateSpecializationType(Name,
2202 &TemplateArgs[0],
2203 TemplateArgs.size(),
Douglas Gregor8c795a12009-03-19 00:39:20 +00002204 Context.getTypeDeclType(Specialization));
Douglas Gregordd13e842009-03-30 22:58:21 +00002205 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00002206 TemplateArgsIn.release();
Douglas Gregora08b6c72009-02-17 23:15:12 +00002207
Douglas Gregor50113ca2009-02-25 22:18:32 +00002208 // C++ [temp.expl.spec]p9:
2209 // A template explicit specialization is in the scope of the
2210 // namespace in which the template was defined.
2211 //
2212 // We actually implement this paragraph where we set the semantic
2213 // context (in the creation of the ClassTemplateSpecializationDecl),
2214 // but we also maintain the lexical context where the actual
2215 // definition occurs.
Douglas Gregora08b6c72009-02-17 23:15:12 +00002216 Specialization->setLexicalDeclContext(CurContext);
2217
2218 // We may be starting the definition of this specialization.
2219 if (TK == TK_Definition)
2220 Specialization->startDefinition();
2221
2222 // Add the specialization into its lexical context, so that it can
2223 // be seen when iterating through the list of declarations in that
2224 // context. However, specializations are not found by name lookup.
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002225 CurContext->addDecl(Context, Specialization);
Chris Lattner5261d0c2009-03-28 19:18:32 +00002226 return DeclPtrTy::make(Specialization);
Douglas Gregora08b6c72009-02-17 23:15:12 +00002227}
Douglas Gregord3022602009-03-27 23:10:48 +00002228
Douglas Gregor96b6df92009-05-14 00:28:11 +00002229// Explicit instantiation of a class template specialization
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002230Sema::DeclResult
2231Sema::ActOnExplicitInstantiation(Scope *S, SourceLocation TemplateLoc,
2232 unsigned TagSpec,
2233 SourceLocation KWLoc,
2234 const CXXScopeSpec &SS,
2235 TemplateTy TemplateD,
2236 SourceLocation TemplateNameLoc,
2237 SourceLocation LAngleLoc,
2238 ASTTemplateArgsPtr TemplateArgsIn,
2239 SourceLocation *TemplateArgLocs,
2240 SourceLocation RAngleLoc,
2241 AttributeList *Attr) {
2242 // Find the class template we're specializing
2243 TemplateName Name = TemplateD.getAsVal<TemplateName>();
2244 ClassTemplateDecl *ClassTemplate
2245 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
2246
2247 // Check that the specialization uses the same tag kind as the
2248 // original template.
2249 TagDecl::TagKind Kind;
2250 switch (TagSpec) {
2251 default: assert(0 && "Unknown tag type!");
2252 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2253 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2254 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2255 }
Douglas Gregor625185c2009-05-14 16:41:31 +00002256 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
2257 Kind, KWLoc,
2258 *ClassTemplate->getIdentifier())) {
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002259 Diag(KWLoc, diag::err_use_with_wrong_tag)
2260 << ClassTemplate
2261 << CodeModificationHint::CreateReplacement(KWLoc,
2262 ClassTemplate->getTemplatedDecl()->getKindName());
2263 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
2264 diag::note_previous_use);
2265 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
2266 }
2267
Douglas Gregor90177912009-05-13 18:28:20 +00002268 // C++0x [temp.explicit]p2:
2269 // [...] An explicit instantiation shall appear in an enclosing
2270 // namespace of its template. [...]
2271 //
2272 // This is C++ DR 275.
2273 if (CheckClassTemplateSpecializationScope(ClassTemplate, 0,
2274 TemplateNameLoc,
2275 SS.getRange(),
2276 /*ExplicitInstantiation=*/true))
2277 return true;
2278
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002279 // Translate the parser's template argument list in our AST format.
2280 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
2281 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
2282
2283 // Check that the template argument list is well-formed for this
2284 // template.
Anders Carlsson558a3a32009-06-05 05:31:27 +00002285 TemplateArgumentListBuilder ConvertedTemplateArgs(Context);
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002286 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
Anders Carlssonb912b392009-06-05 02:12:32 +00002287 TemplateArgs.data(), TemplateArgs.size(),
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002288 RAngleLoc, ConvertedTemplateArgs))
2289 return true;
2290
2291 assert((ConvertedTemplateArgs.size() ==
2292 ClassTemplate->getTemplateParameters()->size()) &&
2293 "Converted template argument list is too short!");
2294
2295 // Find the class template specialization declaration that
2296 // corresponds to these arguments.
2297 llvm::FoldingSetNodeID ID;
Anders Carlssona35faf92009-06-05 03:43:12 +00002298 ClassTemplateSpecializationDecl::Profile(ID,
2299 ConvertedTemplateArgs.getFlatArgumentList(),
2300 ConvertedTemplateArgs.flatSize());
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002301 void *InsertPos = 0;
2302 ClassTemplateSpecializationDecl *PrevDecl
2303 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
2304
2305 ClassTemplateSpecializationDecl *Specialization = 0;
2306
Douglas Gregor90177912009-05-13 18:28:20 +00002307 bool SpecializationRequiresInstantiation = true;
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002308 if (PrevDecl) {
Douglas Gregor90177912009-05-13 18:28:20 +00002309 if (PrevDecl->getSpecializationKind() == TSK_ExplicitInstantiation) {
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002310 // This particular specialization has already been declared or
2311 // instantiated. We cannot explicitly instantiate it.
Douglas Gregor90177912009-05-13 18:28:20 +00002312 Diag(TemplateNameLoc, diag::err_explicit_instantiation_duplicate)
2313 << Context.getTypeDeclType(PrevDecl);
2314 Diag(PrevDecl->getLocation(),
2315 diag::note_previous_explicit_instantiation);
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002316 return DeclPtrTy::make(PrevDecl);
2317 }
2318
Douglas Gregor90177912009-05-13 18:28:20 +00002319 if (PrevDecl->getSpecializationKind() == TSK_ExplicitSpecialization) {
Douglas Gregor96b6df92009-05-14 00:28:11 +00002320 // C++ DR 259, C++0x [temp.explicit]p4:
Douglas Gregor90177912009-05-13 18:28:20 +00002321 // For a given set of template parameters, if an explicit
2322 // instantiation of a template appears after a declaration of
2323 // an explicit specialization for that template, the explicit
2324 // instantiation has no effect.
2325 if (!getLangOptions().CPlusPlus0x) {
2326 Diag(TemplateNameLoc,
2327 diag::ext_explicit_instantiation_after_specialization)
2328 << Context.getTypeDeclType(PrevDecl);
2329 Diag(PrevDecl->getLocation(),
2330 diag::note_previous_template_specialization);
2331 }
2332
2333 // Create a new class template specialization declaration node
2334 // for this explicit specialization. This node is only used to
2335 // record the existence of this explicit instantiation for
2336 // accurate reproduction of the source code; we don't actually
2337 // use it for anything, since it is semantically irrelevant.
2338 Specialization
2339 = ClassTemplateSpecializationDecl::Create(Context,
2340 ClassTemplate->getDeclContext(),
2341 TemplateNameLoc,
2342 ClassTemplate,
Anders Carlsson6e9d02f2009-06-05 04:06:48 +00002343 ConvertedTemplateArgs, 0);
Douglas Gregor90177912009-05-13 18:28:20 +00002344 Specialization->setLexicalDeclContext(CurContext);
2345 CurContext->addDecl(Context, Specialization);
2346 return DeclPtrTy::make(Specialization);
2347 }
2348
2349 // If we have already (implicitly) instantiated this
2350 // specialization, there is less work to do.
2351 if (PrevDecl->getSpecializationKind() == TSK_ImplicitInstantiation)
2352 SpecializationRequiresInstantiation = false;
2353
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002354 // Since the only prior class template specialization with these
2355 // arguments was referenced but not declared, reuse that
2356 // declaration node as our own, updating its source location to
2357 // reflect our new declaration.
2358 Specialization = PrevDecl;
2359 Specialization->setLocation(TemplateNameLoc);
2360 PrevDecl = 0;
2361 } else {
2362 // Create a new class template specialization declaration node for
2363 // this explicit specialization.
2364 Specialization
2365 = ClassTemplateSpecializationDecl::Create(Context,
2366 ClassTemplate->getDeclContext(),
2367 TemplateNameLoc,
2368 ClassTemplate,
Anders Carlsson6e9d02f2009-06-05 04:06:48 +00002369 ConvertedTemplateArgs, 0);
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002370
2371 ClassTemplate->getSpecializations().InsertNode(Specialization,
2372 InsertPos);
2373 }
2374
2375 // Build the fully-sugared type for this explicit instantiation as
2376 // the user wrote in the explicit instantiation itself. This means
2377 // that we'll pretty-print the type retrieved from the
2378 // specialization's declaration the way that the user actually wrote
2379 // the explicit instantiation, rather than formatting the name based
2380 // on the "canonical" representation used to store the template
2381 // arguments in the specialization.
2382 QualType WrittenTy
2383 = Context.getTemplateSpecializationType(Name,
Anders Carlssonefbff322009-06-05 02:45:24 +00002384 TemplateArgs.data(),
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002385 TemplateArgs.size(),
2386 Context.getTypeDeclType(Specialization));
2387 Specialization->setTypeAsWritten(WrittenTy);
2388 TemplateArgsIn.release();
2389
2390 // Add the explicit instantiation into its lexical context. However,
2391 // since explicit instantiations are never found by name lookup, we
2392 // just put it into the declaration context directly.
2393 Specialization->setLexicalDeclContext(CurContext);
2394 CurContext->addDecl(Context, Specialization);
2395
2396 // C++ [temp.explicit]p3:
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002397 // A definition of a class template or class member template
2398 // shall be in scope at the point of the explicit instantiation of
2399 // the class template or class member template.
2400 //
2401 // This check comes when we actually try to perform the
2402 // instantiation.
Douglas Gregor556d8c72009-05-15 17:59:04 +00002403 if (SpecializationRequiresInstantiation)
2404 InstantiateClassTemplateSpecialization(Specialization, true);
Douglas Gregorb12249d2009-05-18 17:01:57 +00002405 else // Instantiate the members of this class template specialization.
Douglas Gregor556d8c72009-05-15 17:59:04 +00002406 InstantiateClassTemplateSpecializationMembers(TemplateLoc, Specialization);
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002407
2408 return DeclPtrTy::make(Specialization);
2409}
2410
Douglas Gregor96b6df92009-05-14 00:28:11 +00002411// Explicit instantiation of a member class of a class template.
2412Sema::DeclResult
2413Sema::ActOnExplicitInstantiation(Scope *S, SourceLocation TemplateLoc,
2414 unsigned TagSpec,
2415 SourceLocation KWLoc,
2416 const CXXScopeSpec &SS,
2417 IdentifierInfo *Name,
2418 SourceLocation NameLoc,
2419 AttributeList *Attr) {
2420
Douglas Gregor71f06032009-05-28 23:31:59 +00002421 bool Owned = false;
Douglas Gregor96b6df92009-05-14 00:28:11 +00002422 DeclPtrTy TagD = ActOnTag(S, TagSpec, Action::TK_Reference,
Douglas Gregor71f06032009-05-28 23:31:59 +00002423 KWLoc, SS, Name, NameLoc, Attr, AS_none, Owned);
Douglas Gregor96b6df92009-05-14 00:28:11 +00002424 if (!TagD)
2425 return true;
2426
2427 TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
2428 if (Tag->isEnum()) {
2429 Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
2430 << Context.getTypeDeclType(Tag);
2431 return true;
2432 }
2433
Douglas Gregord769bfa2009-05-27 17:30:49 +00002434 if (Tag->isInvalidDecl())
2435 return true;
2436
Douglas Gregor96b6df92009-05-14 00:28:11 +00002437 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
2438 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
2439 if (!Pattern) {
2440 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
2441 << Context.getTypeDeclType(Record);
2442 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
2443 return true;
2444 }
2445
2446 // C++0x [temp.explicit]p2:
2447 // [...] An explicit instantiation shall appear in an enclosing
2448 // namespace of its template. [...]
2449 //
2450 // This is C++ DR 275.
2451 if (getLangOptions().CPlusPlus0x) {
Mike Stumpe127ae32009-05-16 07:39:55 +00002452 // FIXME: In C++98, we would like to turn these errors into warnings,
2453 // dependent on a -Wc++0x flag.
Douglas Gregor96b6df92009-05-14 00:28:11 +00002454 DeclContext *PatternContext
2455 = Pattern->getDeclContext()->getEnclosingNamespaceContext();
2456 if (!CurContext->Encloses(PatternContext)) {
2457 Diag(TemplateLoc, diag::err_explicit_instantiation_out_of_scope)
2458 << Record << cast<NamedDecl>(PatternContext) << SS.getRange();
2459 Diag(Pattern->getLocation(), diag::note_previous_declaration);
2460 }
2461 }
2462
Douglas Gregor96b6df92009-05-14 00:28:11 +00002463 if (!Record->getDefinition(Context)) {
2464 // If the class has a definition, instantiate it (and all of its
2465 // members, recursively).
2466 Pattern = cast_or_null<CXXRecordDecl>(Pattern->getDefinition(Context));
2467 if (Pattern && InstantiateClass(TemplateLoc, Record, Pattern,
Douglas Gregor5f62c5e2009-05-14 23:26:13 +00002468 getTemplateInstantiationArgs(Record),
Douglas Gregor96b6df92009-05-14 00:28:11 +00002469 /*ExplicitInstantiation=*/true))
2470 return true;
Douglas Gregorb12249d2009-05-18 17:01:57 +00002471 } else // Instantiate all of the members of class.
Douglas Gregor96b6df92009-05-14 00:28:11 +00002472 InstantiateClassMembers(TemplateLoc, Record,
Douglas Gregor5f62c5e2009-05-14 23:26:13 +00002473 getTemplateInstantiationArgs(Record));
Douglas Gregor96b6df92009-05-14 00:28:11 +00002474
Mike Stumpe127ae32009-05-16 07:39:55 +00002475 // FIXME: We don't have any representation for explicit instantiations of
2476 // member classes. Such a representation is not needed for compilation, but it
2477 // should be available for clients that want to see all of the declarations in
2478 // the source code.
Douglas Gregor96b6df92009-05-14 00:28:11 +00002479 return TagD;
2480}
2481
Douglas Gregord3022602009-03-27 23:10:48 +00002482Sema::TypeResult
2483Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
2484 const IdentifierInfo &II, SourceLocation IdLoc) {
2485 NestedNameSpecifier *NNS
2486 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
2487 if (!NNS)
2488 return true;
2489
2490 QualType T = CheckTypenameType(NNS, II, SourceRange(TypenameLoc, IdLoc));
Douglas Gregord7cb0372009-04-01 21:51:26 +00002491 if (T.isNull())
2492 return true;
Douglas Gregord3022602009-03-27 23:10:48 +00002493 return T.getAsOpaquePtr();
2494}
2495
Douglas Gregor77da5802009-04-01 00:28:59 +00002496Sema::TypeResult
2497Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
2498 SourceLocation TemplateLoc, TypeTy *Ty) {
2499 QualType T = QualType::getFromOpaquePtr(Ty);
2500 NestedNameSpecifier *NNS
2501 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
2502 const TemplateSpecializationType *TemplateId
2503 = T->getAsTemplateSpecializationType();
2504 assert(TemplateId && "Expected a template specialization type");
2505
2506 if (NNS->isDependent())
2507 return Context.getTypenameType(NNS, TemplateId).getAsOpaquePtr();
2508
2509 return Context.getQualifiedNameType(NNS, T).getAsOpaquePtr();
2510}
2511
Douglas Gregord3022602009-03-27 23:10:48 +00002512/// \brief Build the type that describes a C++ typename specifier,
2513/// e.g., "typename T::type".
2514QualType
2515Sema::CheckTypenameType(NestedNameSpecifier *NNS, const IdentifierInfo &II,
2516 SourceRange Range) {
Douglas Gregor3eb20702009-05-11 19:58:34 +00002517 CXXRecordDecl *CurrentInstantiation = 0;
2518 if (NNS->isDependent()) {
2519 CurrentInstantiation = getCurrentInstantiationOf(NNS);
Douglas Gregord3022602009-03-27 23:10:48 +00002520
Douglas Gregor3eb20702009-05-11 19:58:34 +00002521 // If the nested-name-specifier does not refer to the current
2522 // instantiation, then build a typename type.
2523 if (!CurrentInstantiation)
2524 return Context.getTypenameType(NNS, &II);
2525 }
Douglas Gregord3022602009-03-27 23:10:48 +00002526
Douglas Gregor3eb20702009-05-11 19:58:34 +00002527 DeclContext *Ctx = 0;
2528
2529 if (CurrentInstantiation)
2530 Ctx = CurrentInstantiation;
2531 else {
2532 CXXScopeSpec SS;
2533 SS.setScopeRep(NNS);
2534 SS.setRange(Range);
2535 if (RequireCompleteDeclContext(SS))
2536 return QualType();
2537
2538 Ctx = computeDeclContext(SS);
2539 }
Douglas Gregord3022602009-03-27 23:10:48 +00002540 assert(Ctx && "No declaration context?");
2541
2542 DeclarationName Name(&II);
2543 LookupResult Result = LookupQualifiedName(Ctx, Name, LookupOrdinaryName,
2544 false);
2545 unsigned DiagID = 0;
2546 Decl *Referenced = 0;
2547 switch (Result.getKind()) {
2548 case LookupResult::NotFound:
2549 if (Ctx->isTranslationUnit())
2550 DiagID = diag::err_typename_nested_not_found_global;
2551 else
2552 DiagID = diag::err_typename_nested_not_found;
2553 break;
2554
2555 case LookupResult::Found:
2556 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getAsDecl())) {
2557 // We found a type. Build a QualifiedNameType, since the
2558 // typename-specifier was just sugar. FIXME: Tell
2559 // QualifiedNameType that it has a "typename" prefix.
2560 return Context.getQualifiedNameType(NNS, Context.getTypeDeclType(Type));
2561 }
2562
2563 DiagID = diag::err_typename_nested_not_type;
2564 Referenced = Result.getAsDecl();
2565 break;
2566
2567 case LookupResult::FoundOverloaded:
2568 DiagID = diag::err_typename_nested_not_type;
2569 Referenced = *Result.begin();
2570 break;
2571
2572 case LookupResult::AmbiguousBaseSubobjectTypes:
2573 case LookupResult::AmbiguousBaseSubobjects:
2574 case LookupResult::AmbiguousReference:
2575 DiagnoseAmbiguousLookup(Result, Name, Range.getEnd(), Range);
2576 return QualType();
2577 }
2578
2579 // If we get here, it's because name lookup did not find a
2580 // type. Emit an appropriate diagnostic and return an error.
2581 if (NamedDecl *NamedCtx = dyn_cast<NamedDecl>(Ctx))
2582 Diag(Range.getEnd(), DiagID) << Range << Name << NamedCtx;
2583 else
2584 Diag(Range.getEnd(), DiagID) << Range << Name;
2585 if (Referenced)
2586 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
2587 << Name;
2588 return QualType();
2589}