blob: d72fcf8adcd61dff5c555493efb75e892c248ac6 [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 Gregor9614dad2009-06-24 00:23:40 +000070 // FIXME: What follows is a slightly less gross hack than what used to
71 // follow.
Douglas Gregor2fa10442008-12-18 19:37:40 +000072 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(IIDecl)) {
Douglas Gregor9614dad2009-06-24 00:23:40 +000073 if (FD->getDescribedFunctionTemplate()) {
Douglas Gregordd13e842009-03-30 22:58:21 +000074 TemplateResult = TemplateTy::make(FD);
Douglas Gregor8e458f42009-02-09 18:46:07 +000075 return TNK_Function_template;
76 }
Douglas Gregor2fa10442008-12-18 19:37:40 +000077 } else if (OverloadedFunctionDecl *Ovl
78 = dyn_cast<OverloadedFunctionDecl>(IIDecl)) {
79 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
80 FEnd = Ovl->function_end();
81 F != FEnd; ++F) {
Douglas Gregorb60eb752009-06-25 22:08:12 +000082 if (isa<FunctionTemplateDecl>(*F)) {
Douglas Gregordd13e842009-03-30 22:58:21 +000083 TemplateResult = TemplateTy::make(Ovl);
Douglas Gregor8e458f42009-02-09 18:46:07 +000084 return TNK_Function_template;
85 }
Douglas Gregor2fa10442008-12-18 19:37:40 +000086 }
87 }
Douglas Gregordd13e842009-03-30 22:58:21 +000088
89 if (TNK != TNK_Non_template) {
90 if (SS && SS->isSet() && !SS->isInvalid()) {
91 NestedNameSpecifier *Qualifier
92 = static_cast<NestedNameSpecifier *>(SS->getScopeRep());
93 TemplateResult
94 = TemplateTy::make(Context.getQualifiedTemplateName(Qualifier,
95 false,
96 Template));
97 } else
98 TemplateResult = TemplateTy::make(TemplateName(Template));
99 }
Douglas Gregor2fa10442008-12-18 19:37:40 +0000100 }
Douglas Gregordd13e842009-03-30 22:58:21 +0000101 return TNK;
Douglas Gregor2fa10442008-12-18 19:37:40 +0000102}
103
Douglas Gregordd861062008-12-05 18:15:24 +0000104/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
105/// that the template parameter 'PrevDecl' is being shadowed by a new
106/// declaration at location Loc. Returns true to indicate that this is
107/// an error, and false otherwise.
108bool Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
Douglas Gregor2715a1f2008-12-08 18:40:42 +0000109 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregordd861062008-12-05 18:15:24 +0000110
111 // Microsoft Visual C++ permits template parameters to be shadowed.
112 if (getLangOptions().Microsoft)
113 return false;
114
115 // C++ [temp.local]p4:
116 // A template-parameter shall not be redeclared within its
117 // scope (including nested scopes).
118 Diag(Loc, diag::err_template_param_shadow)
119 << cast<NamedDecl>(PrevDecl)->getDeclName();
120 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
121 return true;
122}
123
Douglas Gregored3a3982009-03-03 04:44:36 +0000124/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregor279272e2009-02-04 19:02:06 +0000125/// the parameter D to reference the templated declaration and return a pointer
126/// to the template declaration. Otherwise, do nothing to D and return null.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000127TemplateDecl *Sema::AdjustDeclIfTemplate(DeclPtrTy &D) {
128 if (TemplateDecl *Temp = dyn_cast<TemplateDecl>(D.getAs<Decl>())) {
129 D = DeclPtrTy::make(Temp->getTemplatedDecl());
Douglas Gregor279272e2009-02-04 19:02:06 +0000130 return Temp;
131 }
132 return 0;
133}
134
Douglas Gregordd861062008-12-05 18:15:24 +0000135/// ActOnTypeParameter - Called when a C++ template type parameter
136/// (e.g., "typename T") has been parsed. Typename specifies whether
137/// the keyword "typename" was used to declare the type parameter
138/// (otherwise, "class" was used), and KeyLoc is the location of the
139/// "class" or "typename" keyword. ParamName is the name of the
140/// parameter (NULL indicates an unnamed template parameter) and
141/// ParamName is the location of the parameter name (if any).
142/// If the type parameter has a default argument, it will be added
143/// later via ActOnTypeParameterDefault.
Anders Carlsson9c85fa02009-06-12 19:58:00 +0000144Sema::DeclPtrTy Sema::ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis,
145 SourceLocation EllipsisLoc,
Chris Lattner5261d0c2009-03-28 19:18:32 +0000146 SourceLocation KeyLoc,
147 IdentifierInfo *ParamName,
148 SourceLocation ParamNameLoc,
149 unsigned Depth, unsigned Position) {
Douglas Gregordd861062008-12-05 18:15:24 +0000150 assert(S->isTemplateParamScope() &&
151 "Template type parameter not in template parameter scope!");
152 bool Invalid = false;
153
154 if (ParamName) {
Douglas Gregor09be81b2009-02-04 17:27:36 +0000155 NamedDecl *PrevDecl = LookupName(S, ParamName, LookupTagName);
Douglas Gregor2715a1f2008-12-08 18:40:42 +0000156 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregordd861062008-12-05 18:15:24 +0000157 Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc,
158 PrevDecl);
159 }
160
Douglas Gregord406b032009-02-06 22:42:48 +0000161 SourceLocation Loc = ParamNameLoc;
162 if (!ParamName)
163 Loc = KeyLoc;
164
Douglas Gregordd861062008-12-05 18:15:24 +0000165 TemplateTypeParmDecl *Param
Douglas Gregord406b032009-02-06 22:42:48 +0000166 = TemplateTypeParmDecl::Create(Context, CurContext, Loc,
Anders Carlssoneebbf9a2009-06-12 22:23:22 +0000167 Depth, Position, ParamName, Typename,
168 Ellipsis);
Douglas Gregordd861062008-12-05 18:15:24 +0000169 if (Invalid)
170 Param->setInvalidDecl();
171
172 if (ParamName) {
173 // Add the template parameter into the current scope.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000174 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregordd861062008-12-05 18:15:24 +0000175 IdResolver.AddDecl(Param);
176 }
177
Chris Lattner5261d0c2009-03-28 19:18:32 +0000178 return DeclPtrTy::make(Param);
Douglas Gregordd861062008-12-05 18:15:24 +0000179}
180
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000181/// ActOnTypeParameterDefault - Adds a default argument (the type
182/// Default) to the given template type parameter (TypeParam).
Chris Lattner5261d0c2009-03-28 19:18:32 +0000183void Sema::ActOnTypeParameterDefault(DeclPtrTy TypeParam,
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000184 SourceLocation EqualLoc,
185 SourceLocation DefaultLoc,
186 TypeTy *DefaultT) {
187 TemplateTypeParmDecl *Parm
Chris Lattner5261d0c2009-03-28 19:18:32 +0000188 = cast<TemplateTypeParmDecl>(TypeParam.getAs<Decl>());
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000189 QualType Default = QualType::getFromOpaquePtr(DefaultT);
190
Anders Carlssona2333782009-06-12 22:30:13 +0000191 // C++0x [temp.param]p9:
192 // A default template-argument may be specified for any kind of
193 // template-parameter that is not a template parameter pack.
194 if (Parm->isParameterPack()) {
195 Diag(DefaultLoc, diag::err_template_param_pack_default_arg);
Anders Carlssona2333782009-06-12 22:30:13 +0000196 return;
197 }
198
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000199 // C++ [temp.param]p14:
200 // A template-parameter shall not be used in its own default argument.
201 // FIXME: Implement this check! Needs a recursive walk over the types.
202
203 // Check the template argument itself.
204 if (CheckTemplateArgument(Parm, Default, DefaultLoc)) {
205 Parm->setInvalidDecl();
206 return;
207 }
208
209 Parm->setDefaultArgument(Default, DefaultLoc, false);
210}
211
Douglas Gregored3a3982009-03-03 04:44:36 +0000212/// \brief Check that the type of a non-type template parameter is
213/// well-formed.
214///
215/// \returns the (possibly-promoted) parameter type if valid;
216/// otherwise, produces a diagnostic and returns a NULL type.
217QualType
218Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
219 // C++ [temp.param]p4:
220 //
221 // A non-type template-parameter shall have one of the following
222 // (optionally cv-qualified) types:
223 //
224 // -- integral or enumeration type,
225 if (T->isIntegralType() || T->isEnumeralType() ||
226 // -- pointer to object or pointer to function,
227 (T->isPointerType() &&
228 (T->getAsPointerType()->getPointeeType()->isObjectType() ||
229 T->getAsPointerType()->getPointeeType()->isFunctionType())) ||
230 // -- reference to object or reference to function,
231 T->isReferenceType() ||
232 // -- pointer to member.
233 T->isMemberPointerType() ||
234 // If T is a dependent type, we can't do the check now, so we
235 // assume that it is well-formed.
236 T->isDependentType())
237 return T;
238 // C++ [temp.param]p8:
239 //
240 // A non-type template-parameter of type "array of T" or
241 // "function returning T" is adjusted to be of type "pointer to
242 // T" or "pointer to function returning T", respectively.
243 else if (T->isArrayType())
244 // FIXME: Keep the type prior to promotion?
245 return Context.getArrayDecayedType(T);
246 else if (T->isFunctionType())
247 // FIXME: Keep the type prior to promotion?
248 return Context.getPointerType(T);
249
250 Diag(Loc, diag::err_template_nontype_parm_bad_type)
251 << T;
252
253 return QualType();
254}
255
Douglas Gregordd861062008-12-05 18:15:24 +0000256/// ActOnNonTypeTemplateParameter - Called when a C++ non-type
257/// template parameter (e.g., "int Size" in "template<int Size>
258/// class Array") has been parsed. S is the current scope and D is
259/// the parsed declarator.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000260Sema::DeclPtrTy Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
261 unsigned Depth,
262 unsigned Position) {
Douglas Gregordd861062008-12-05 18:15:24 +0000263 QualType T = GetTypeForDeclarator(D, S);
264
Douglas Gregor279272e2009-02-04 19:02:06 +0000265 assert(S->isTemplateParamScope() &&
266 "Non-type template parameter not in template parameter scope!");
Douglas Gregordd861062008-12-05 18:15:24 +0000267 bool Invalid = false;
268
269 IdentifierInfo *ParamName = D.getIdentifier();
270 if (ParamName) {
Douglas Gregor09be81b2009-02-04 17:27:36 +0000271 NamedDecl *PrevDecl = LookupName(S, ParamName, LookupTagName);
Douglas Gregor2715a1f2008-12-08 18:40:42 +0000272 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregordd861062008-12-05 18:15:24 +0000273 Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
Douglas Gregor279272e2009-02-04 19:02:06 +0000274 PrevDecl);
Douglas Gregordd861062008-12-05 18:15:24 +0000275 }
276
Douglas Gregored3a3982009-03-03 04:44:36 +0000277 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
Douglas Gregor8b90e8e2009-03-09 16:46:39 +0000278 if (T.isNull()) {
Douglas Gregored3a3982009-03-03 04:44:36 +0000279 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregor8b90e8e2009-03-09 16:46:39 +0000280 Invalid = true;
281 }
Douglas Gregor62cdc792009-02-10 17:43:50 +0000282
Douglas Gregordd861062008-12-05 18:15:24 +0000283 NonTypeTemplateParmDecl *Param
284 = NonTypeTemplateParmDecl::Create(Context, CurContext, D.getIdentifierLoc(),
Douglas Gregor279272e2009-02-04 19:02:06 +0000285 Depth, Position, ParamName, T);
Douglas Gregordd861062008-12-05 18:15:24 +0000286 if (Invalid)
287 Param->setInvalidDecl();
288
289 if (D.getIdentifier()) {
290 // Add the template parameter into the current scope.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000291 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregordd861062008-12-05 18:15:24 +0000292 IdResolver.AddDecl(Param);
293 }
Chris Lattner5261d0c2009-03-28 19:18:32 +0000294 return DeclPtrTy::make(Param);
Douglas Gregordd861062008-12-05 18:15:24 +0000295}
Douglas Gregor52473432008-12-24 02:52:09 +0000296
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000297/// \brief Adds a default argument to the given non-type template
298/// parameter.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000299void Sema::ActOnNonTypeTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000300 SourceLocation EqualLoc,
301 ExprArg DefaultE) {
302 NonTypeTemplateParmDecl *TemplateParm
Chris Lattner5261d0c2009-03-28 19:18:32 +0000303 = cast<NonTypeTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000304 Expr *Default = static_cast<Expr *>(DefaultE.get());
305
306 // C++ [temp.param]p14:
307 // A template-parameter shall not be used in its own default argument.
308 // FIXME: Implement this check! Needs a recursive walk over the types.
309
310 // Check the well-formedness of the default template argument.
Douglas Gregor8f378a92009-06-11 18:10:32 +0000311 TemplateArgument Converted;
312 if (CheckTemplateArgument(TemplateParm, TemplateParm->getType(), Default,
313 Converted)) {
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000314 TemplateParm->setInvalidDecl();
315 return;
316 }
317
Anders Carlsson39ecdcf2009-05-01 19:49:17 +0000318 TemplateParm->setDefaultArgument(DefaultE.takeAs<Expr>());
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000319}
320
Douglas Gregor279272e2009-02-04 19:02:06 +0000321
322/// ActOnTemplateTemplateParameter - Called when a C++ template template
323/// parameter (e.g. T in template <template <typename> class T> class array)
324/// has been parsed. S is the current scope.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000325Sema::DeclPtrTy Sema::ActOnTemplateTemplateParameter(Scope* S,
326 SourceLocation TmpLoc,
327 TemplateParamsTy *Params,
328 IdentifierInfo *Name,
329 SourceLocation NameLoc,
330 unsigned Depth,
331 unsigned Position)
Douglas Gregor279272e2009-02-04 19:02:06 +0000332{
333 assert(S->isTemplateParamScope() &&
334 "Template template parameter not in template parameter scope!");
335
336 // Construct the parameter object.
337 TemplateTemplateParmDecl *Param =
338 TemplateTemplateParmDecl::Create(Context, CurContext, TmpLoc, Depth,
339 Position, Name,
340 (TemplateParameterList*)Params);
341
342 // Make sure the parameter is valid.
343 // FIXME: Decl object is not currently invalidated anywhere so this doesn't
344 // do anything yet. However, if the template parameter list or (eventual)
345 // default value is ever invalidated, that will propagate here.
346 bool Invalid = false;
347 if (Invalid) {
348 Param->setInvalidDecl();
349 }
350
351 // If the tt-param has a name, then link the identifier into the scope
352 // and lookup mechanisms.
353 if (Name) {
Chris Lattner5261d0c2009-03-28 19:18:32 +0000354 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor279272e2009-02-04 19:02:06 +0000355 IdResolver.AddDecl(Param);
356 }
357
Chris Lattner5261d0c2009-03-28 19:18:32 +0000358 return DeclPtrTy::make(Param);
Douglas Gregor279272e2009-02-04 19:02:06 +0000359}
360
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000361/// \brief Adds a default argument to the given template template
362/// parameter.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000363void Sema::ActOnTemplateTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000364 SourceLocation EqualLoc,
365 ExprArg DefaultE) {
366 TemplateTemplateParmDecl *TemplateParm
Chris Lattner5261d0c2009-03-28 19:18:32 +0000367 = cast<TemplateTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000368
369 // Since a template-template parameter's default argument is an
370 // id-expression, it must be a DeclRefExpr.
371 DeclRefExpr *Default
372 = cast<DeclRefExpr>(static_cast<Expr *>(DefaultE.get()));
373
374 // C++ [temp.param]p14:
375 // A template-parameter shall not be used in its own default argument.
376 // FIXME: Implement this check! Needs a recursive walk over the types.
377
378 // Check the well-formedness of the template argument.
379 if (!isa<TemplateDecl>(Default->getDecl())) {
380 Diag(Default->getSourceRange().getBegin(),
381 diag::err_template_arg_must_be_template)
382 << Default->getSourceRange();
383 TemplateParm->setInvalidDecl();
384 return;
385 }
386 if (CheckTemplateArgument(TemplateParm, Default)) {
387 TemplateParm->setInvalidDecl();
388 return;
389 }
390
391 DefaultE.release();
392 TemplateParm->setDefaultArgument(Default);
393}
394
Douglas Gregor52473432008-12-24 02:52:09 +0000395/// ActOnTemplateParameterList - Builds a TemplateParameterList that
396/// contains the template parameters in Params/NumParams.
397Sema::TemplateParamsTy *
398Sema::ActOnTemplateParameterList(unsigned Depth,
399 SourceLocation ExportLoc,
400 SourceLocation TemplateLoc,
401 SourceLocation LAngleLoc,
Chris Lattner5261d0c2009-03-28 19:18:32 +0000402 DeclPtrTy *Params, unsigned NumParams,
Douglas Gregor52473432008-12-24 02:52:09 +0000403 SourceLocation RAngleLoc) {
404 if (ExportLoc.isValid())
405 Diag(ExportLoc, diag::note_template_export_unsupported);
406
Douglas Gregord406b032009-02-06 22:42:48 +0000407 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
408 (Decl**)Params, NumParams, RAngleLoc);
Douglas Gregor52473432008-12-24 02:52:09 +0000409}
Douglas Gregor279272e2009-02-04 19:02:06 +0000410
Douglas Gregorc5d6fa72009-03-25 00:13:59 +0000411Sema::DeclResult
Douglas Gregord406b032009-02-06 22:42:48 +0000412Sema::ActOnClassTemplate(Scope *S, unsigned TagSpec, TagKind TK,
413 SourceLocation KWLoc, const CXXScopeSpec &SS,
414 IdentifierInfo *Name, SourceLocation NameLoc,
415 AttributeList *Attr,
Anders Carlssoned20fb92009-03-26 00:52:18 +0000416 MultiTemplateParamsArg TemplateParameterLists,
417 AccessSpecifier AS) {
Douglas Gregord406b032009-02-06 22:42:48 +0000418 assert(TemplateParameterLists.size() > 0 && "No template parameter lists?");
419 assert(TK != TK_Reference && "Can only declare or define class templates");
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000420 bool Invalid = false;
Douglas Gregord406b032009-02-06 22:42:48 +0000421
422 // Check that we can declare a template here.
423 if (CheckTemplateDeclScope(S, TemplateParameterLists))
Douglas Gregorc5d6fa72009-03-25 00:13:59 +0000424 return true;
Douglas Gregord406b032009-02-06 22:42:48 +0000425
426 TagDecl::TagKind Kind;
427 switch (TagSpec) {
428 default: assert(0 && "Unknown tag type!");
429 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
430 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
431 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
432 }
433
434 // There is no such thing as an unnamed class template.
435 if (!Name) {
436 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregorc5d6fa72009-03-25 00:13:59 +0000437 return true;
Douglas Gregord406b032009-02-06 22:42:48 +0000438 }
439
440 // Find any previous declaration with this name.
441 LookupResult Previous = LookupParsedName(S, &SS, Name, LookupOrdinaryName,
442 true);
443 assert(!Previous.isAmbiguous() && "Ambiguity in class template redecl?");
444 NamedDecl *PrevDecl = 0;
445 if (Previous.begin() != Previous.end())
446 PrevDecl = *Previous.begin();
447
Douglas Gregor23521802009-06-17 23:37:01 +0000448 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
449 PrevDecl = 0;
450
Douglas Gregord406b032009-02-06 22:42:48 +0000451 DeclContext *SemanticContext = CurContext;
452 if (SS.isNotEmpty() && !SS.isInvalid()) {
Douglas Gregor734b4ba2009-03-19 00:18:19 +0000453 SemanticContext = computeDeclContext(SS);
Douglas Gregord406b032009-02-06 22:42:48 +0000454
Mike Stumpe127ae32009-05-16 07:39:55 +0000455 // FIXME: need to match up several levels of template parameter lists here.
Douglas Gregord406b032009-02-06 22:42:48 +0000456 }
457
458 // FIXME: member templates!
459 TemplateParameterList *TemplateParams
460 = static_cast<TemplateParameterList *>(*TemplateParameterLists.release());
461
462 // If there is a previous declaration with the same name, check
463 // whether this is a valid redeclaration.
464 ClassTemplateDecl *PrevClassTemplate
465 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
466 if (PrevClassTemplate) {
467 // Ensure that the template parameter lists are compatible.
468 if (!TemplateParameterListsAreEqual(TemplateParams,
469 PrevClassTemplate->getTemplateParameters(),
470 /*Complain=*/true))
Douglas Gregorc5d6fa72009-03-25 00:13:59 +0000471 return true;
Douglas Gregord406b032009-02-06 22:42:48 +0000472
473 // C++ [temp.class]p4:
474 // In a redeclaration, partial specialization, explicit
475 // specialization or explicit instantiation of a class template,
476 // the class-key shall agree in kind with the original class
477 // template declaration (7.1.5.3).
478 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Douglas Gregor625185c2009-05-14 16:41:31 +0000479 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind, KWLoc, *Name)) {
Douglas Gregor3faaa812009-04-01 23:51:29 +0000480 Diag(KWLoc, diag::err_use_with_wrong_tag)
481 << Name
482 << CodeModificationHint::CreateReplacement(KWLoc,
483 PrevRecordDecl->getKindName());
Douglas Gregord406b032009-02-06 22:42:48 +0000484 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregor3faaa812009-04-01 23:51:29 +0000485 Kind = PrevRecordDecl->getTagKind();
Douglas Gregord406b032009-02-06 22:42:48 +0000486 }
487
Douglas Gregord406b032009-02-06 22:42:48 +0000488 // Check for redefinition of this class template.
489 if (TK == TK_Definition) {
490 if (TagDecl *Def = PrevRecordDecl->getDefinition(Context)) {
491 Diag(NameLoc, diag::err_redefinition) << Name;
492 Diag(Def->getLocation(), diag::note_previous_definition);
493 // FIXME: Would it make sense to try to "forget" the previous
494 // definition, as part of error recovery?
Douglas Gregorc5d6fa72009-03-25 00:13:59 +0000495 return true;
Douglas Gregord406b032009-02-06 22:42:48 +0000496 }
497 }
498 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
499 // Maybe we will complain about the shadowed template parameter.
500 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
501 // Just pretend that we didn't see the previous declaration.
502 PrevDecl = 0;
503 } else if (PrevDecl) {
504 // C++ [temp]p5:
505 // A class template shall not have the same name as any other
506 // template, class, function, object, enumeration, enumerator,
507 // namespace, or type in the same scope (3.3), except as specified
508 // in (14.5.4).
509 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
510 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregorc5d6fa72009-03-25 00:13:59 +0000511 return true;
Douglas Gregord406b032009-02-06 22:42:48 +0000512 }
513
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000514 // Check the template parameter list of this declaration, possibly
515 // merging in the template parameter list from the previous class
516 // template declaration.
517 if (CheckTemplateParameterList(TemplateParams,
518 PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0))
519 Invalid = true;
520
Douglas Gregor9054f982009-05-10 22:57:19 +0000521 // FIXME: If we had a scope specifier, we better have a previous template
Douglas Gregord406b032009-02-06 22:42:48 +0000522 // declaration!
523
Douglas Gregor55216ac2009-03-26 00:10:35 +0000524 CXXRecordDecl *NewClass =
Douglas Gregord406b032009-02-06 22:42:48 +0000525 CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name,
526 PrevClassTemplate?
Douglas Gregor12aed0b2009-05-15 19:11:46 +0000527 PrevClassTemplate->getTemplatedDecl() : 0,
528 /*DelayTypeCreation=*/true);
Douglas Gregord406b032009-02-06 22:42:48 +0000529
530 ClassTemplateDecl *NewTemplate
531 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
532 DeclarationName(Name), TemplateParams,
Douglas Gregor47bde7c2009-03-19 17:26:29 +0000533 NewClass, PrevClassTemplate);
Douglas Gregor55216ac2009-03-26 00:10:35 +0000534 NewClass->setDescribedClassTemplate(NewTemplate);
535
Douglas Gregor12aed0b2009-05-15 19:11:46 +0000536 // Build the type for the class template declaration now.
537 QualType T =
538 Context.getTypeDeclType(NewClass,
539 PrevClassTemplate?
540 PrevClassTemplate->getTemplatedDecl() : 0);
541 assert(T->isDependentType() && "Class template type is not dependent?");
542 (void)T;
543
Anders Carlsson4ca43492009-03-26 01:24:28 +0000544 // Set the access specifier.
545 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
546
Douglas Gregord406b032009-02-06 22:42:48 +0000547 // Set the lexical context of these templates
548 NewClass->setLexicalDeclContext(CurContext);
549 NewTemplate->setLexicalDeclContext(CurContext);
550
551 if (TK == TK_Definition)
552 NewClass->startDefinition();
553
554 if (Attr)
Douglas Gregor2a2e0402009-06-17 21:51:59 +0000555 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregord406b032009-02-06 22:42:48 +0000556
557 PushOnScopeChains(NewTemplate, S);
558
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000559 if (Invalid) {
560 NewTemplate->setInvalidDecl();
561 NewClass->setInvalidDecl();
562 }
Chris Lattner5261d0c2009-03-28 19:18:32 +0000563 return DeclPtrTy::make(NewTemplate);
Douglas Gregord406b032009-02-06 22:42:48 +0000564}
565
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000566/// \brief Checks the validity of a template parameter list, possibly
567/// considering the template parameter list from a previous
568/// declaration.
569///
570/// If an "old" template parameter list is provided, it must be
571/// equivalent (per TemplateParameterListsAreEqual) to the "new"
572/// template parameter list.
573///
574/// \param NewParams Template parameter list for a new template
575/// declaration. This template parameter list will be updated with any
576/// default arguments that are carried through from the previous
577/// template parameter list.
578///
579/// \param OldParams If provided, template parameter list from a
580/// previous declaration of the same template. Default template
581/// arguments will be merged from the old template parameter list to
582/// the new template parameter list.
583///
584/// \returns true if an error occurred, false otherwise.
585bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
586 TemplateParameterList *OldParams) {
587 bool Invalid = false;
588
589 // C++ [temp.param]p10:
590 // The set of default template-arguments available for use with a
591 // template declaration or definition is obtained by merging the
592 // default arguments from the definition (if in scope) and all
593 // declarations in scope in the same way default function
594 // arguments are (8.3.6).
595 bool SawDefaultArgument = false;
596 SourceLocation PreviousDefaultArgLoc;
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000597
Anders Carlssonb1929502009-06-12 23:20:15 +0000598 bool SawParameterPack = false;
599 SourceLocation ParameterPackLoc;
600
Mike Stumpe0b7e032009-02-11 23:03:27 +0000601 // Dummy initialization to avoid warnings.
Douglas Gregorc5363f42009-02-11 20:46:19 +0000602 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000603 if (OldParams)
604 OldParam = OldParams->begin();
605
606 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
607 NewParamEnd = NewParams->end();
608 NewParam != NewParamEnd; ++NewParam) {
609 // Variables used to diagnose redundant default arguments
610 bool RedundantDefaultArg = false;
611 SourceLocation OldDefaultLoc;
612 SourceLocation NewDefaultLoc;
613
614 // Variables used to diagnose missing default arguments
615 bool MissingDefaultArg = false;
616
Anders Carlssonb1929502009-06-12 23:20:15 +0000617 // C++0x [temp.param]p11:
618 // If a template parameter of a class template is a template parameter pack,
619 // it must be the last template parameter.
620 if (SawParameterPack) {
621 Diag(ParameterPackLoc,
622 diag::err_template_param_pack_must_be_last_template_parameter);
623 Invalid = true;
624 }
625
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000626 // Merge default arguments for template type parameters.
627 if (TemplateTypeParmDecl *NewTypeParm
628 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
629 TemplateTypeParmDecl *OldTypeParm
630 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
631
Anders Carlssonb1929502009-06-12 23:20:15 +0000632 if (NewTypeParm->isParameterPack()) {
633 assert(!NewTypeParm->hasDefaultArgument() &&
634 "Parameter packs can't have a default argument!");
635 SawParameterPack = true;
636 ParameterPackLoc = NewTypeParm->getLocation();
637 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000638 NewTypeParm->hasDefaultArgument()) {
639 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
640 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
641 SawDefaultArgument = true;
642 RedundantDefaultArg = true;
643 PreviousDefaultArgLoc = NewDefaultLoc;
644 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
645 // Merge the default argument from the old declaration to the
646 // new declaration.
647 SawDefaultArgument = true;
648 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgument(),
649 OldTypeParm->getDefaultArgumentLoc(),
650 true);
651 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
652 } else if (NewTypeParm->hasDefaultArgument()) {
653 SawDefaultArgument = true;
654 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
655 } else if (SawDefaultArgument)
656 MissingDefaultArg = true;
657 }
658 // Merge default arguments for non-type template parameters
659 else if (NonTypeTemplateParmDecl *NewNonTypeParm
660 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
661 NonTypeTemplateParmDecl *OldNonTypeParm
662 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
663 if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
664 NewNonTypeParm->hasDefaultArgument()) {
665 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
666 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
667 SawDefaultArgument = true;
668 RedundantDefaultArg = true;
669 PreviousDefaultArgLoc = NewDefaultLoc;
670 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
671 // Merge the default argument from the old declaration to the
672 // new declaration.
673 SawDefaultArgument = true;
674 // FIXME: We need to create a new kind of "default argument"
675 // expression that points to a previous template template
676 // parameter.
677 NewNonTypeParm->setDefaultArgument(
678 OldNonTypeParm->getDefaultArgument());
679 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
680 } else if (NewNonTypeParm->hasDefaultArgument()) {
681 SawDefaultArgument = true;
682 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
683 } else if (SawDefaultArgument)
684 MissingDefaultArg = true;
685 }
686 // Merge default arguments for template template parameters
687 else {
688 TemplateTemplateParmDecl *NewTemplateParm
689 = cast<TemplateTemplateParmDecl>(*NewParam);
690 TemplateTemplateParmDecl *OldTemplateParm
691 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
692 if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
693 NewTemplateParm->hasDefaultArgument()) {
694 OldDefaultLoc = OldTemplateParm->getDefaultArgumentLoc();
695 NewDefaultLoc = NewTemplateParm->getDefaultArgumentLoc();
696 SawDefaultArgument = true;
697 RedundantDefaultArg = true;
698 PreviousDefaultArgLoc = NewDefaultLoc;
699 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
700 // Merge the default argument from the old declaration to the
701 // new declaration.
702 SawDefaultArgument = true;
Mike Stumpe127ae32009-05-16 07:39:55 +0000703 // FIXME: We need to create a new kind of "default argument" expression
704 // that points to a previous template template parameter.
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000705 NewTemplateParm->setDefaultArgument(
706 OldTemplateParm->getDefaultArgument());
707 PreviousDefaultArgLoc = OldTemplateParm->getDefaultArgumentLoc();
708 } else if (NewTemplateParm->hasDefaultArgument()) {
709 SawDefaultArgument = true;
710 PreviousDefaultArgLoc = NewTemplateParm->getDefaultArgumentLoc();
711 } else if (SawDefaultArgument)
712 MissingDefaultArg = true;
713 }
714
715 if (RedundantDefaultArg) {
716 // C++ [temp.param]p12:
717 // A template-parameter shall not be given default arguments
718 // by two different declarations in the same scope.
719 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
720 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
721 Invalid = true;
722 } else if (MissingDefaultArg) {
723 // C++ [temp.param]p11:
724 // If a template-parameter has a default template-argument,
725 // all subsequent template-parameters shall have a default
726 // template-argument supplied.
727 Diag((*NewParam)->getLocation(),
728 diag::err_template_param_default_arg_missing);
729 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
730 Invalid = true;
731 }
732
733 // If we have an old template parameter list that we're merging
734 // in, move on to the next parameter.
735 if (OldParams)
736 ++OldParam;
737 }
738
739 return Invalid;
740}
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000741
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000742/// \brief Translates template arguments as provided by the parser
743/// into template arguments used by semantic analysis.
744static void
745translateTemplateArguments(ASTTemplateArgsPtr &TemplateArgsIn,
746 SourceLocation *TemplateArgLocs,
747 llvm::SmallVector<TemplateArgument, 16> &TemplateArgs) {
748 TemplateArgs.reserve(TemplateArgsIn.size());
749
750 void **Args = TemplateArgsIn.getArgs();
751 bool *ArgIsType = TemplateArgsIn.getArgIsType();
752 for (unsigned Arg = 0, Last = TemplateArgsIn.size(); Arg != Last; ++Arg) {
753 TemplateArgs.push_back(
754 ArgIsType[Arg]? TemplateArgument(TemplateArgLocs[Arg],
755 QualType::getFromOpaquePtr(Args[Arg]))
756 : TemplateArgument(reinterpret_cast<Expr *>(Args[Arg])));
757 }
758}
759
Douglas Gregoraabb8502009-03-31 00:43:58 +0000760/// \brief Build a canonical version of a template argument list.
761///
762/// This function builds a canonical version of the given template
763/// argument list, where each of the template arguments has been
764/// converted into its canonical form. This routine is typically used
765/// to canonicalize a template argument list when the template name
766/// itself is dependent. When the template name refers to an actual
767/// template declaration, Sema::CheckTemplateArgumentList should be
768/// used to check and canonicalize the template arguments.
769///
770/// \param TemplateArgs The incoming template arguments.
771///
772/// \param NumTemplateArgs The number of template arguments in \p
773/// TemplateArgs.
774///
775/// \param Canonical A vector to be filled with the canonical versions
776/// of the template arguments.
777///
778/// \param Context The ASTContext in which the template arguments live.
779static void CanonicalizeTemplateArguments(const TemplateArgument *TemplateArgs,
780 unsigned NumTemplateArgs,
781 llvm::SmallVectorImpl<TemplateArgument> &Canonical,
782 ASTContext &Context) {
783 Canonical.reserve(NumTemplateArgs);
784 for (unsigned Idx = 0; Idx < NumTemplateArgs; ++Idx) {
785 switch (TemplateArgs[Idx].getKind()) {
Douglas Gregorbf23a8a2009-06-04 00:03:07 +0000786 case TemplateArgument::Null:
787 assert(false && "Should never see a NULL template argument here");
788 break;
789
Douglas Gregoraabb8502009-03-31 00:43:58 +0000790 case TemplateArgument::Expression:
791 // FIXME: Build canonical expression (!)
792 Canonical.push_back(TemplateArgs[Idx]);
793 break;
794
795 case TemplateArgument::Declaration:
Douglas Gregor9054f982009-05-10 22:57:19 +0000796 Canonical.push_back(
797 TemplateArgument(SourceLocation(),
798 Context.getCanonicalDecl(TemplateArgs[Idx].getAsDecl())));
Douglas Gregoraabb8502009-03-31 00:43:58 +0000799 break;
800
801 case TemplateArgument::Integral:
802 Canonical.push_back(TemplateArgument(SourceLocation(),
803 *TemplateArgs[Idx].getAsIntegral(),
804 TemplateArgs[Idx].getIntegralType()));
Douglas Gregorbf23a8a2009-06-04 00:03:07 +0000805 break;
Douglas Gregoraabb8502009-03-31 00:43:58 +0000806
807 case TemplateArgument::Type: {
808 QualType CanonType
809 = Context.getCanonicalType(TemplateArgs[Idx].getAsType());
810 Canonical.push_back(TemplateArgument(SourceLocation(), CanonType));
Douglas Gregorbf23a8a2009-06-04 00:03:07 +0000811 break;
Douglas Gregoraabb8502009-03-31 00:43:58 +0000812 }
Anders Carlsson584b5062009-06-15 17:04:53 +0000813
814 case TemplateArgument::Pack:
815 assert(0 && "FIXME: Implement!");
816 break;
Douglas Gregoraabb8502009-03-31 00:43:58 +0000817 }
818 }
819}
820
Douglas Gregordd13e842009-03-30 22:58:21 +0000821QualType Sema::CheckTemplateIdType(TemplateName Name,
822 SourceLocation TemplateLoc,
823 SourceLocation LAngleLoc,
824 const TemplateArgument *TemplateArgs,
825 unsigned NumTemplateArgs,
826 SourceLocation RAngleLoc) {
827 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregoraabb8502009-03-31 00:43:58 +0000828 if (!Template) {
829 // The template name does not resolve to a template, so we just
830 // build a dependent template-id type.
831
832 // Canonicalize the template arguments to build the canonical
833 // template-id type.
834 llvm::SmallVector<TemplateArgument, 16> CanonicalTemplateArgs;
835 CanonicalizeTemplateArguments(TemplateArgs, NumTemplateArgs,
836 CanonicalTemplateArgs, Context);
837
Douglas Gregor905406b2009-05-07 06:49:52 +0000838 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
Douglas Gregoraabb8502009-03-31 00:43:58 +0000839 QualType CanonType
Douglas Gregor905406b2009-05-07 06:49:52 +0000840 = Context.getTemplateSpecializationType(CanonName,
841 &CanonicalTemplateArgs[0],
Douglas Gregoraabb8502009-03-31 00:43:58 +0000842 CanonicalTemplateArgs.size());
843
844 // Build the dependent template-id type.
845 return Context.getTemplateSpecializationType(Name, TemplateArgs,
846 NumTemplateArgs, CanonType);
847 }
Douglas Gregordd13e842009-03-30 22:58:21 +0000848
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000849 // Check that the template argument list is well-formed for this
850 // template.
Anders Carlssonb0fc9992009-06-23 01:26:57 +0000851 TemplateArgumentListBuilder Converted(Template->getTemplateParameters(),
852 NumTemplateArgs);
Douglas Gregordd13e842009-03-30 22:58:21 +0000853 if (CheckTemplateArgumentList(Template, TemplateLoc, LAngleLoc,
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000854 TemplateArgs, NumTemplateArgs, RAngleLoc,
Anders Carlssonb0fc9992009-06-23 01:26:57 +0000855 Converted))
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000856 return QualType();
857
Anders Carlssonb0fc9992009-06-23 01:26:57 +0000858 assert((Converted.structuredSize() ==
Douglas Gregordd13e842009-03-30 22:58:21 +0000859 Template->getTemplateParameters()->size()) &&
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000860 "Converted template argument list is too short!");
861
862 QualType CanonType;
863
Douglas Gregordd13e842009-03-30 22:58:21 +0000864 if (TemplateSpecializationType::anyDependentTemplateArguments(
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000865 TemplateArgs,
866 NumTemplateArgs)) {
867 // This class template specialization is a dependent
868 // type. Therefore, its canonical type is another class template
869 // specialization type that contains all of the converted
870 // arguments in canonical form. This ensures that, e.g., A<T> and
871 // A<T, T> have identical types when A is declared as:
872 //
873 // template<typename T, typename U = T> struct A;
Douglas Gregorb88ba412009-05-07 06:41:52 +0000874 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
875 CanonType = Context.getTemplateSpecializationType(CanonName,
Anders Carlssonb0fc9992009-06-23 01:26:57 +0000876 Converted.getFlatArguments(),
877 Converted.flatSize());
Douglas Gregordd13e842009-03-30 22:58:21 +0000878 } else if (ClassTemplateDecl *ClassTemplate
879 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000880 // Find the class template specialization declaration that
881 // corresponds to these arguments.
882 llvm::FoldingSetNodeID ID;
Anders Carlssona35faf92009-06-05 03:43:12 +0000883 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlssonb0fc9992009-06-23 01:26:57 +0000884 Converted.getFlatArguments(),
885 Converted.flatSize());
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000886 void *InsertPos = 0;
887 ClassTemplateSpecializationDecl *Decl
888 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
889 if (!Decl) {
890 // This is the first time we have referenced this class template
891 // specialization. Create the canonical declaration and add it to
892 // the set of specializations.
893 Decl = ClassTemplateSpecializationDecl::Create(Context,
Anders Carlssona35faf92009-06-05 03:43:12 +0000894 ClassTemplate->getDeclContext(),
895 TemplateLoc,
896 ClassTemplate,
Anders Carlssonb0fc9992009-06-23 01:26:57 +0000897 Converted, 0);
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000898 ClassTemplate->getSpecializations().InsertNode(Decl, InsertPos);
899 Decl->setLexicalDeclContext(CurContext);
900 }
901
902 CanonType = Context.getTypeDeclType(Decl);
903 }
904
905 // Build the fully-sugared type for this class template
906 // specialization, which refers back to the class template
907 // specialization we created or found.
Douglas Gregordd13e842009-03-30 22:58:21 +0000908 return Context.getTemplateSpecializationType(Name, TemplateArgs,
909 NumTemplateArgs, CanonType);
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000910}
911
Douglas Gregora08b6c72009-02-17 23:15:12 +0000912Action::TypeResult
Douglas Gregordd13e842009-03-30 22:58:21 +0000913Sema::ActOnTemplateIdType(TemplateTy TemplateD, SourceLocation TemplateLoc,
914 SourceLocation LAngleLoc,
915 ASTTemplateArgsPtr TemplateArgsIn,
916 SourceLocation *TemplateArgLocs,
917 SourceLocation RAngleLoc) {
918 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Douglas Gregor8e458f42009-02-09 18:46:07 +0000919
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000920 // Translate the parser's template argument list in our AST format.
921 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
922 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000923
Douglas Gregordd13e842009-03-30 22:58:21 +0000924 QualType Result = CheckTemplateIdType(Template, TemplateLoc, LAngleLoc,
Jay Foad9e6bef42009-05-21 09:52:38 +0000925 TemplateArgs.data(),
926 TemplateArgs.size(),
Douglas Gregordd13e842009-03-30 22:58:21 +0000927 RAngleLoc);
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000928 TemplateArgsIn.release();
Douglas Gregord7cb0372009-04-01 21:51:26 +0000929
930 if (Result.isNull())
931 return true;
932
Douglas Gregor6f37b582009-02-09 19:34:22 +0000933 return Result.getAsOpaquePtr();
Douglas Gregor8e458f42009-02-09 18:46:07 +0000934}
935
Douglas Gregor28857752009-06-30 22:34:41 +0000936Sema::OwningExprResult Sema::BuildTemplateIdExpr(TemplateName Template,
937 SourceLocation TemplateNameLoc,
938 SourceLocation LAngleLoc,
939 const TemplateArgument *TemplateArgs,
940 unsigned NumTemplateArgs,
941 SourceLocation RAngleLoc) {
942 // FIXME: Can we do any checking at this point? I guess we could check the
943 // template arguments that we have against the template name, if the template
944 // name refers to a single template. That's not a terribly common case,
945 // though.
946 return Owned(TemplateIdRefExpr::Create(Context,
947 /*FIXME: New type?*/Context.OverloadTy,
948 /*FIXME: Necessary?*/0,
949 /*FIXME: Necessary?*/SourceRange(),
950 Template, TemplateNameLoc, LAngleLoc,
951 TemplateArgs,
952 NumTemplateArgs, RAngleLoc));
953}
954
955Sema::OwningExprResult Sema::ActOnTemplateIdExpr(TemplateTy TemplateD,
956 SourceLocation TemplateNameLoc,
957 SourceLocation LAngleLoc,
958 ASTTemplateArgsPtr TemplateArgsIn,
959 SourceLocation *TemplateArgLocs,
960 SourceLocation RAngleLoc) {
961 TemplateName Template = TemplateD.getAsVal<TemplateName>();
962
963 // Translate the parser's template argument list in our AST format.
964 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
965 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
966
967 return BuildTemplateIdExpr(Template, TemplateNameLoc, LAngleLoc,
968 TemplateArgs.data(), TemplateArgs.size(),
969 RAngleLoc);
970}
971
Douglas Gregoraabb8502009-03-31 00:43:58 +0000972/// \brief Form a dependent template name.
973///
974/// This action forms a dependent template name given the template
975/// name and its (presumably dependent) scope specifier. For
976/// example, given "MetaFun::template apply", the scope specifier \p
977/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
978/// of the "template" keyword, and "apply" is the \p Name.
979Sema::TemplateTy
980Sema::ActOnDependentTemplateName(SourceLocation TemplateKWLoc,
981 const IdentifierInfo &Name,
982 SourceLocation NameLoc,
983 const CXXScopeSpec &SS) {
984 if (!SS.isSet() || SS.isInvalid())
985 return TemplateTy();
986
987 NestedNameSpecifier *Qualifier
988 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
989
990 // FIXME: member of the current instantiation
991
992 if (!Qualifier->isDependent()) {
993 // C++0x [temp.names]p5:
994 // If a name prefixed by the keyword template is not the name of
995 // a template, the program is ill-formed. [Note: the keyword
996 // template may not be applied to non-template members of class
997 // templates. -end note ] [ Note: as is the case with the
998 // typename prefix, the template prefix is allowed in cases
999 // where it is not strictly necessary; i.e., when the
1000 // nested-name-specifier or the expression on the left of the ->
1001 // or . is not dependent on a template-parameter, or the use
1002 // does not appear in the scope of a template. -end note]
1003 //
1004 // Note: C++03 was more strict here, because it banned the use of
1005 // the "template" keyword prior to a template-name that was not a
1006 // dependent name. C++ DR468 relaxed this requirement (the
1007 // "template" keyword is now permitted). We follow the C++0x
1008 // rules, even in C++03 mode, retroactively applying the DR.
1009 TemplateTy Template;
1010 TemplateNameKind TNK = isTemplateName(Name, 0, Template, &SS);
1011 if (TNK == TNK_Non_template) {
1012 Diag(NameLoc, diag::err_template_kw_refers_to_non_template)
1013 << &Name;
1014 return TemplateTy();
1015 }
1016
1017 return Template;
1018 }
1019
1020 return TemplateTy::make(Context.getDependentTemplateName(Qualifier, &Name));
1021}
1022
Anders Carlssonfdd33cc2009-06-13 00:33:33 +00001023bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
1024 const TemplateArgument &Arg,
1025 TemplateArgumentListBuilder &Converted) {
1026 // Check template type parameter.
1027 if (Arg.getKind() != TemplateArgument::Type) {
1028 // C++ [temp.arg.type]p1:
1029 // A template-argument for a template-parameter which is a
1030 // type shall be a type-id.
1031
1032 // We have a template type parameter but the template argument
1033 // is not a type.
1034 Diag(Arg.getLocation(), diag::err_template_arg_must_be_type);
1035 Diag(Param->getLocation(), diag::note_template_param_here);
1036
1037 return true;
1038 }
1039
1040 if (CheckTemplateArgument(Param, Arg.getAsType(), Arg.getLocation()))
1041 return true;
1042
1043 // Add the converted template type argument.
Anders Carlssonb0fc9992009-06-23 01:26:57 +00001044 Converted.Append(
Anders Carlssonfdd33cc2009-06-13 00:33:33 +00001045 TemplateArgument(Arg.getLocation(),
1046 Context.getCanonicalType(Arg.getAsType())));
1047 return false;
1048}
1049
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001050/// \brief Check that the given template argument list is well-formed
1051/// for specializing the given template.
1052bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
1053 SourceLocation TemplateLoc,
1054 SourceLocation LAngleLoc,
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001055 const TemplateArgument *TemplateArgs,
1056 unsigned NumTemplateArgs,
Douglas Gregorad964b32009-02-17 01:05:43 +00001057 SourceLocation RAngleLoc,
Anders Carlssona35faf92009-06-05 03:43:12 +00001058 TemplateArgumentListBuilder &Converted) {
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001059 TemplateParameterList *Params = Template->getTemplateParameters();
1060 unsigned NumParams = Params->size();
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001061 unsigned NumArgs = NumTemplateArgs;
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001062 bool Invalid = false;
1063
Anders Carlsson4ffb5812009-06-13 02:08:00 +00001064 bool HasParameterPack =
1065 NumParams > 0 && Params->getParam(NumParams - 1)->isTemplateParameterPack();
1066
1067 if ((NumArgs > NumParams && !HasParameterPack) ||
Douglas Gregorc347d8e2009-02-11 18:16:40 +00001068 NumArgs < Params->getMinRequiredArguments()) {
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001069 // FIXME: point at either the first arg beyond what we can handle,
1070 // or the '>', depending on whether we have too many or too few
1071 // arguments.
1072 SourceRange Range;
1073 if (NumArgs > NumParams)
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001074 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001075 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
1076 << (NumArgs > NumParams)
1077 << (isa<ClassTemplateDecl>(Template)? 0 :
1078 isa<FunctionTemplateDecl>(Template)? 1 :
1079 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
1080 << Template << Range;
Douglas Gregorc347d8e2009-02-11 18:16:40 +00001081 Diag(Template->getLocation(), diag::note_template_decl_here)
1082 << Params->getSourceRange();
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001083 Invalid = true;
1084 }
1085
1086 // C++ [temp.arg]p1:
1087 // [...] The type and form of each template-argument specified in
1088 // a template-id shall match the type and form specified for the
1089 // corresponding parameter declared by the template in its
1090 // template-parameter-list.
1091 unsigned ArgIdx = 0;
1092 for (TemplateParameterList::iterator Param = Params->begin(),
1093 ParamEnd = Params->end();
1094 Param != ParamEnd; ++Param, ++ArgIdx) {
1095 // Decode the template argument
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001096 TemplateArgument Arg;
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001097 if (ArgIdx >= NumArgs) {
Douglas Gregorad964b32009-02-17 01:05:43 +00001098 // Retrieve the default template argument from the template
1099 // parameter.
1100 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
Anders Carlsson4ffb5812009-06-13 02:08:00 +00001101 if (TTP->isParameterPack()) {
Anders Carlssonb0fc9992009-06-23 01:26:57 +00001102 // We have an empty argument pack.
1103 Converted.BeginPack();
1104 Converted.EndPack();
Anders Carlsson4ffb5812009-06-13 02:08:00 +00001105 break;
1106 }
1107
Douglas Gregorad964b32009-02-17 01:05:43 +00001108 if (!TTP->hasDefaultArgument())
1109 break;
1110
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001111 QualType ArgType = TTP->getDefaultArgument();
Douglas Gregor74296542009-02-27 19:31:52 +00001112
1113 // If the argument type is dependent, instantiate it now based
1114 // on the previously-computed template arguments.
Douglas Gregor56d25a72009-03-10 20:44:00 +00001115 if (ArgType->isDependentType()) {
1116 InstantiatingTemplate Inst(*this, TemplateLoc,
Anders Carlssonb0fc9992009-06-23 01:26:57 +00001117 Template, Converted.getFlatArguments(),
Anders Carlssona35faf92009-06-05 03:43:12 +00001118 Converted.flatSize(),
Douglas Gregor56d25a72009-03-10 20:44:00 +00001119 SourceRange(TemplateLoc, RAngleLoc));
Douglas Gregorf9e7d3d2009-05-11 23:53:27 +00001120
Anders Carlsson0233eb62009-06-05 04:47:51 +00001121 TemplateArgumentList TemplateArgs(Context, Converted,
Anders Carlssonb0fc9992009-06-23 01:26:57 +00001122 /*TakeArgs=*/false);
Douglas Gregorf9e7d3d2009-05-11 23:53:27 +00001123 ArgType = InstantiateType(ArgType, TemplateArgs,
Douglas Gregor74296542009-02-27 19:31:52 +00001124 TTP->getDefaultArgumentLoc(),
1125 TTP->getDeclName());
Douglas Gregor56d25a72009-03-10 20:44:00 +00001126 }
Douglas Gregor74296542009-02-27 19:31:52 +00001127
1128 if (ArgType.isNull())
Douglas Gregorf57dcd02009-02-28 00:25:32 +00001129 return true;
Douglas Gregor74296542009-02-27 19:31:52 +00001130
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001131 Arg = TemplateArgument(TTP->getLocation(), ArgType);
Douglas Gregorad964b32009-02-17 01:05:43 +00001132 } else if (NonTypeTemplateParmDecl *NTTP
1133 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
1134 if (!NTTP->hasDefaultArgument())
1135 break;
1136
Anders Carlsson0297caf2009-06-11 16:06:49 +00001137 InstantiatingTemplate Inst(*this, TemplateLoc,
Anders Carlssonb0fc9992009-06-23 01:26:57 +00001138 Template, Converted.getFlatArguments(),
Anders Carlsson0297caf2009-06-11 16:06:49 +00001139 Converted.flatSize(),
1140 SourceRange(TemplateLoc, RAngleLoc));
1141
1142 TemplateArgumentList TemplateArgs(Context, Converted,
Anders Carlssonb0fc9992009-06-23 01:26:57 +00001143 /*TakeArgs=*/false);
Anders Carlsson0297caf2009-06-11 16:06:49 +00001144
1145 Sema::OwningExprResult E = InstantiateExpr(NTTP->getDefaultArgument(),
1146 TemplateArgs);
1147 if (E.isInvalid())
1148 return true;
1149
1150 Arg = TemplateArgument(E.takeAs<Expr>());
Douglas Gregorad964b32009-02-17 01:05:43 +00001151 } else {
1152 TemplateTemplateParmDecl *TempParm
1153 = cast<TemplateTemplateParmDecl>(*Param);
1154
1155 if (!TempParm->hasDefaultArgument())
1156 break;
1157
Douglas Gregored3a3982009-03-03 04:44:36 +00001158 // FIXME: Instantiate default argument
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001159 Arg = TemplateArgument(TempParm->getDefaultArgument());
Douglas Gregorad964b32009-02-17 01:05:43 +00001160 }
1161 } else {
1162 // Retrieve the template argument produced by the user.
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001163 Arg = TemplateArgs[ArgIdx];
Douglas Gregorad964b32009-02-17 01:05:43 +00001164 }
1165
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001166
1167 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
Anders Carlsson4ffb5812009-06-13 02:08:00 +00001168 if (TTP->isParameterPack()) {
Anders Carlssonb0fc9992009-06-23 01:26:57 +00001169 Converted.BeginPack();
Anders Carlsson4ffb5812009-06-13 02:08:00 +00001170 // Check all the remaining arguments (if any).
1171 for (; ArgIdx < NumArgs; ++ArgIdx) {
1172 if (CheckTemplateTypeArgument(TTP, TemplateArgs[ArgIdx], Converted))
1173 Invalid = true;
1174 }
1175
Anders Carlssonb0fc9992009-06-23 01:26:57 +00001176 Converted.EndPack();
Anders Carlsson4ffb5812009-06-13 02:08:00 +00001177 } else {
1178 if (CheckTemplateTypeArgument(TTP, Arg, Converted))
1179 Invalid = true;
1180 }
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001181 } else if (NonTypeTemplateParmDecl *NTTP
1182 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
1183 // Check non-type template parameters.
Douglas Gregored3a3982009-03-03 04:44:36 +00001184
1185 // Instantiate the type of the non-type template parameter with
1186 // the template arguments we've seen thus far.
1187 QualType NTTPType = NTTP->getType();
1188 if (NTTPType->isDependentType()) {
1189 // Instantiate the type of the non-type template parameter.
Douglas Gregor56d25a72009-03-10 20:44:00 +00001190 InstantiatingTemplate Inst(*this, TemplateLoc,
Anders Carlssonb0fc9992009-06-23 01:26:57 +00001191 Template, Converted.getFlatArguments(),
Anders Carlssona35faf92009-06-05 03:43:12 +00001192 Converted.flatSize(),
Douglas Gregor56d25a72009-03-10 20:44:00 +00001193 SourceRange(TemplateLoc, RAngleLoc));
1194
Anders Carlsson0233eb62009-06-05 04:47:51 +00001195 TemplateArgumentList TemplateArgs(Context, Converted,
Anders Carlssonb0fc9992009-06-23 01:26:57 +00001196 /*TakeArgs=*/false);
Douglas Gregorf9e7d3d2009-05-11 23:53:27 +00001197 NTTPType = InstantiateType(NTTPType, TemplateArgs,
Douglas Gregored3a3982009-03-03 04:44:36 +00001198 NTTP->getLocation(),
1199 NTTP->getDeclName());
1200 // If that worked, check the non-type template parameter type
1201 // for validity.
1202 if (!NTTPType.isNull())
1203 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
1204 NTTP->getLocation());
Douglas Gregored3a3982009-03-03 04:44:36 +00001205 if (NTTPType.isNull()) {
1206 Invalid = true;
1207 break;
1208 }
1209 }
1210
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001211 switch (Arg.getKind()) {
Douglas Gregorbf23a8a2009-06-04 00:03:07 +00001212 case TemplateArgument::Null:
1213 assert(false && "Should never see a NULL template argument here");
1214 break;
1215
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001216 case TemplateArgument::Expression: {
1217 Expr *E = Arg.getAsExpr();
Douglas Gregor8f378a92009-06-11 18:10:32 +00001218 TemplateArgument Result;
1219 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001220 Invalid = true;
Douglas Gregor8f378a92009-06-11 18:10:32 +00001221 else
Anders Carlssonb0fc9992009-06-23 01:26:57 +00001222 Converted.Append(Result);
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001223 break;
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001224 }
1225
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001226 case TemplateArgument::Declaration:
1227 case TemplateArgument::Integral:
1228 // We've already checked this template argument, so just copy
1229 // it to the list of converted arguments.
Anders Carlssonb0fc9992009-06-23 01:26:57 +00001230 Converted.Append(Arg);
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001231 break;
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001232
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001233 case TemplateArgument::Type:
1234 // We have a non-type template parameter but the template
1235 // argument is a type.
1236
1237 // C++ [temp.arg]p2:
1238 // In a template-argument, an ambiguity between a type-id and
1239 // an expression is resolved to a type-id, regardless of the
1240 // form of the corresponding template-parameter.
1241 //
1242 // We warn specifically about this case, since it can be rather
1243 // confusing for users.
1244 if (Arg.getAsType()->isFunctionType())
1245 Diag(Arg.getLocation(), diag::err_template_arg_nontype_ambig)
1246 << Arg.getAsType();
1247 else
1248 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr);
1249 Diag((*Param)->getLocation(), diag::note_template_param_here);
1250 Invalid = true;
Anders Carlsson584b5062009-06-15 17:04:53 +00001251 break;
1252
1253 case TemplateArgument::Pack:
1254 assert(0 && "FIXME: Implement!");
1255 break;
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001256 }
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001257 } else {
1258 // Check template template parameters.
1259 TemplateTemplateParmDecl *TempParm
1260 = cast<TemplateTemplateParmDecl>(*Param);
1261
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001262 switch (Arg.getKind()) {
Douglas Gregorbf23a8a2009-06-04 00:03:07 +00001263 case TemplateArgument::Null:
1264 assert(false && "Should never see a NULL template argument here");
1265 break;
1266
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001267 case TemplateArgument::Expression: {
1268 Expr *ArgExpr = Arg.getAsExpr();
1269 if (ArgExpr && isa<DeclRefExpr>(ArgExpr) &&
1270 isa<TemplateDecl>(cast<DeclRefExpr>(ArgExpr)->getDecl())) {
1271 if (CheckTemplateArgument(TempParm, cast<DeclRefExpr>(ArgExpr)))
1272 Invalid = true;
1273
1274 // Add the converted template argument.
Douglas Gregor9054f982009-05-10 22:57:19 +00001275 Decl *D
1276 = Context.getCanonicalDecl(cast<DeclRefExpr>(ArgExpr)->getDecl());
Anders Carlssonb0fc9992009-06-23 01:26:57 +00001277 Converted.Append(TemplateArgument(Arg.getLocation(), D));
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001278 continue;
1279 }
1280 }
1281 // fall through
1282
1283 case TemplateArgument::Type: {
1284 // We have a template template parameter but the template
1285 // argument does not refer to a template.
1286 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
1287 Invalid = true;
1288 break;
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001289 }
1290
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001291 case TemplateArgument::Declaration:
1292 // We've already checked this template argument, so just copy
1293 // it to the list of converted arguments.
Anders Carlssonb0fc9992009-06-23 01:26:57 +00001294 Converted.Append(Arg);
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001295 break;
1296
1297 case TemplateArgument::Integral:
1298 assert(false && "Integral argument with template template parameter");
1299 break;
Anders Carlsson584b5062009-06-15 17:04:53 +00001300
1301 case TemplateArgument::Pack:
1302 assert(0 && "FIXME: Implement!");
1303 break;
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001304 }
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001305 }
1306 }
1307
1308 return Invalid;
1309}
1310
1311/// \brief Check a template argument against its corresponding
1312/// template type parameter.
1313///
1314/// This routine implements the semantics of C++ [temp.arg.type]. It
1315/// returns true if an error occurred, and false otherwise.
1316bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
1317 QualType Arg, SourceLocation ArgLoc) {
1318 // C++ [temp.arg.type]p2:
1319 // A local type, a type with no linkage, an unnamed type or a type
1320 // compounded from any of these types shall not be used as a
1321 // template-argument for a template type-parameter.
1322 //
1323 // FIXME: Perform the recursive and no-linkage type checks.
1324 const TagType *Tag = 0;
1325 if (const EnumType *EnumT = Arg->getAsEnumType())
1326 Tag = EnumT;
1327 else if (const RecordType *RecordT = Arg->getAsRecordType())
1328 Tag = RecordT;
1329 if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod())
1330 return Diag(ArgLoc, diag::err_template_arg_local_type)
1331 << QualType(Tag, 0);
Douglas Gregor04385782009-03-10 18:33:27 +00001332 else if (Tag && !Tag->getDecl()->getDeclName() &&
1333 !Tag->getDecl()->getTypedefForAnonDecl()) {
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001334 Diag(ArgLoc, diag::err_template_arg_unnamed_type);
1335 Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here);
1336 return true;
1337 }
1338
1339 return false;
1340}
1341
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001342/// \brief Checks whether the given template argument is the address
1343/// of an object or function according to C++ [temp.arg.nontype]p1.
Douglas Gregorad964b32009-02-17 01:05:43 +00001344bool Sema::CheckTemplateArgumentAddressOfObjectOrFunction(Expr *Arg,
1345 NamedDecl *&Entity) {
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001346 bool Invalid = false;
1347
1348 // See through any implicit casts we added to fix the type.
1349 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
1350 Arg = Cast->getSubExpr();
1351
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001352 // C++0x allows nullptr, and there's no further checking to be done for that.
1353 if (Arg->getType()->isNullPtrType())
1354 return false;
1355
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001356 // C++ [temp.arg.nontype]p1:
1357 //
1358 // A template-argument for a non-type, non-template
1359 // template-parameter shall be one of: [...]
1360 //
1361 // -- the address of an object or function with external
1362 // linkage, including function templates and function
1363 // template-ids but excluding non-static class members,
1364 // expressed as & id-expression where the & is optional if
1365 // the name refers to a function or array, or if the
1366 // corresponding template-parameter is a reference; or
1367 DeclRefExpr *DRE = 0;
1368
1369 // Ignore (and complain about) any excess parentheses.
1370 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
1371 if (!Invalid) {
1372 Diag(Arg->getSourceRange().getBegin(),
1373 diag::err_template_arg_extra_parens)
1374 << Arg->getSourceRange();
1375 Invalid = true;
1376 }
1377
1378 Arg = Parens->getSubExpr();
1379 }
1380
1381 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
1382 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
1383 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
1384 } else
1385 DRE = dyn_cast<DeclRefExpr>(Arg);
1386
1387 if (!DRE || !isa<ValueDecl>(DRE->getDecl()))
1388 return Diag(Arg->getSourceRange().getBegin(),
1389 diag::err_template_arg_not_object_or_func_form)
1390 << Arg->getSourceRange();
1391
1392 // Cannot refer to non-static data members
1393 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl()))
1394 return Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
1395 << Field << Arg->getSourceRange();
1396
1397 // Cannot refer to non-static member functions
1398 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
1399 if (!Method->isStatic())
1400 return Diag(Arg->getSourceRange().getBegin(),
1401 diag::err_template_arg_method)
1402 << Method << Arg->getSourceRange();
1403
1404 // Functions must have external linkage.
1405 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
1406 if (Func->getStorageClass() == FunctionDecl::Static) {
1407 Diag(Arg->getSourceRange().getBegin(),
1408 diag::err_template_arg_function_not_extern)
1409 << Func << Arg->getSourceRange();
1410 Diag(Func->getLocation(), diag::note_template_arg_internal_object)
1411 << true;
1412 return true;
1413 }
1414
1415 // Okay: we've named a function with external linkage.
Douglas Gregorad964b32009-02-17 01:05:43 +00001416 Entity = Func;
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001417 return Invalid;
1418 }
1419
1420 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
1421 if (!Var->hasGlobalStorage()) {
1422 Diag(Arg->getSourceRange().getBegin(),
1423 diag::err_template_arg_object_not_extern)
1424 << Var << Arg->getSourceRange();
1425 Diag(Var->getLocation(), diag::note_template_arg_internal_object)
1426 << true;
1427 return true;
1428 }
1429
1430 // Okay: we've named an object with external linkage
Douglas Gregorad964b32009-02-17 01:05:43 +00001431 Entity = Var;
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001432 return Invalid;
1433 }
1434
1435 // We found something else, but we don't know specifically what it is.
1436 Diag(Arg->getSourceRange().getBegin(),
1437 diag::err_template_arg_not_object_or_func)
1438 << Arg->getSourceRange();
1439 Diag(DRE->getDecl()->getLocation(),
1440 diag::note_template_arg_refers_here);
1441 return true;
1442}
1443
1444/// \brief Checks whether the given template argument is a pointer to
1445/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregorad964b32009-02-17 01:05:43 +00001446bool
1447Sema::CheckTemplateArgumentPointerToMember(Expr *Arg, NamedDecl *&Member) {
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001448 bool Invalid = false;
1449
1450 // See through any implicit casts we added to fix the type.
1451 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
1452 Arg = Cast->getSubExpr();
1453
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001454 // C++0x allows nullptr, and there's no further checking to be done for that.
1455 if (Arg->getType()->isNullPtrType())
1456 return false;
1457
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001458 // C++ [temp.arg.nontype]p1:
1459 //
1460 // A template-argument for a non-type, non-template
1461 // template-parameter shall be one of: [...]
1462 //
1463 // -- a pointer to member expressed as described in 5.3.1.
1464 QualifiedDeclRefExpr *DRE = 0;
1465
1466 // Ignore (and complain about) any excess parentheses.
1467 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
1468 if (!Invalid) {
1469 Diag(Arg->getSourceRange().getBegin(),
1470 diag::err_template_arg_extra_parens)
1471 << Arg->getSourceRange();
1472 Invalid = true;
1473 }
1474
1475 Arg = Parens->getSubExpr();
1476 }
1477
1478 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg))
1479 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
1480 DRE = dyn_cast<QualifiedDeclRefExpr>(UnOp->getSubExpr());
1481
1482 if (!DRE)
1483 return Diag(Arg->getSourceRange().getBegin(),
1484 diag::err_template_arg_not_pointer_to_member_form)
1485 << Arg->getSourceRange();
1486
1487 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
1488 assert((isa<FieldDecl>(DRE->getDecl()) ||
1489 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
1490 "Only non-static member pointers can make it here");
1491
1492 // Okay: this is the address of a non-static member, and therefore
1493 // a member pointer constant.
Douglas Gregorad964b32009-02-17 01:05:43 +00001494 Member = DRE->getDecl();
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001495 return Invalid;
1496 }
1497
1498 // We found something else, but we don't know specifically what it is.
1499 Diag(Arg->getSourceRange().getBegin(),
1500 diag::err_template_arg_not_pointer_to_member_form)
1501 << Arg->getSourceRange();
1502 Diag(DRE->getDecl()->getLocation(),
1503 diag::note_template_arg_refers_here);
1504 return true;
1505}
1506
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001507/// \brief Check a template argument against its corresponding
1508/// non-type template parameter.
1509///
Douglas Gregored3a3982009-03-03 04:44:36 +00001510/// This routine implements the semantics of C++ [temp.arg.nontype].
1511/// It returns true if an error occurred, and false otherwise. \p
1512/// InstantiatedParamType is the type of the non-type template
1513/// parameter after it has been instantiated.
Douglas Gregorad964b32009-02-17 01:05:43 +00001514///
Douglas Gregor8f378a92009-06-11 18:10:32 +00001515/// If no error was detected, Converted receives the converted template argument.
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001516bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Douglas Gregored3a3982009-03-03 04:44:36 +00001517 QualType InstantiatedParamType, Expr *&Arg,
Douglas Gregor8f378a92009-06-11 18:10:32 +00001518 TemplateArgument &Converted) {
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001519 SourceLocation StartLoc = Arg->getSourceRange().getBegin();
1520
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001521 // If either the parameter has a dependent type or the argument is
1522 // type-dependent, there's nothing we can check now.
Douglas Gregorad964b32009-02-17 01:05:43 +00001523 // FIXME: Add template argument to Converted!
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001524 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
1525 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor8f378a92009-06-11 18:10:32 +00001526 Converted = TemplateArgument(Arg);
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001527 return false;
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001528 }
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001529
1530 // C++ [temp.arg.nontype]p5:
1531 // The following conversions are performed on each expression used
1532 // as a non-type template-argument. If a non-type
1533 // template-argument cannot be converted to the type of the
1534 // corresponding template-parameter then the program is
1535 // ill-formed.
1536 //
1537 // -- for a non-type template-parameter of integral or
1538 // enumeration type, integral promotions (4.5) and integral
1539 // conversions (4.7) are applied.
Douglas Gregored3a3982009-03-03 04:44:36 +00001540 QualType ParamType = InstantiatedParamType;
Douglas Gregor2eedd992009-02-11 00:19:33 +00001541 QualType ArgType = Arg->getType();
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001542 if (ParamType->isIntegralType() || ParamType->isEnumeralType()) {
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001543 // C++ [temp.arg.nontype]p1:
1544 // A template-argument for a non-type, non-template
1545 // template-parameter shall be one of:
1546 //
1547 // -- an integral constant-expression of integral or enumeration
1548 // type; or
1549 // -- the name of a non-type template-parameter; or
1550 SourceLocation NonConstantLoc;
Douglas Gregorad964b32009-02-17 01:05:43 +00001551 llvm::APSInt Value;
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001552 if (!ArgType->isIntegralType() && !ArgType->isEnumeralType()) {
1553 Diag(Arg->getSourceRange().getBegin(),
1554 diag::err_template_arg_not_integral_or_enumeral)
1555 << ArgType << Arg->getSourceRange();
1556 Diag(Param->getLocation(), diag::note_template_param_here);
1557 return true;
1558 } else if (!Arg->isValueDependent() &&
Douglas Gregorad964b32009-02-17 01:05:43 +00001559 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001560 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
1561 << ArgType << Arg->getSourceRange();
1562 return true;
1563 }
1564
1565 // FIXME: We need some way to more easily get the unqualified form
1566 // of the types without going all the way to the
1567 // canonical type.
1568 if (Context.getCanonicalType(ParamType).getCVRQualifiers())
1569 ParamType = Context.getCanonicalType(ParamType).getUnqualifiedType();
1570 if (Context.getCanonicalType(ArgType).getCVRQualifiers())
1571 ArgType = Context.getCanonicalType(ArgType).getUnqualifiedType();
1572
1573 // Try to convert the argument to the parameter's type.
1574 if (ParamType == ArgType) {
1575 // Okay: no conversion necessary
1576 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
1577 !ParamType->isEnumeralType()) {
1578 // This is an integral promotion or conversion.
1579 ImpCastExprToType(Arg, ParamType);
1580 } else {
1581 // We can't perform this conversion.
1582 Diag(Arg->getSourceRange().getBegin(),
1583 diag::err_template_arg_not_convertible)
Douglas Gregored3a3982009-03-03 04:44:36 +00001584 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001585 Diag(Param->getLocation(), diag::note_template_param_here);
1586 return true;
1587 }
1588
Douglas Gregorafc86942009-03-14 00:20:21 +00001589 QualType IntegerType = Context.getCanonicalType(ParamType);
1590 if (const EnumType *Enum = IntegerType->getAsEnumType())
Douglas Gregor8f378a92009-06-11 18:10:32 +00001591 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregorafc86942009-03-14 00:20:21 +00001592
1593 if (!Arg->isValueDependent()) {
1594 // Check that an unsigned parameter does not receive a negative
1595 // value.
1596 if (IntegerType->isUnsignedIntegerType()
1597 && (Value.isSigned() && Value.isNegative())) {
1598 Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_negative)
1599 << Value.toString(10) << Param->getType()
1600 << Arg->getSourceRange();
1601 Diag(Param->getLocation(), diag::note_template_param_here);
1602 return true;
1603 }
1604
1605 // Check that we don't overflow the template parameter type.
1606 unsigned AllowedBits = Context.getTypeSize(IntegerType);
1607 if (Value.getActiveBits() > AllowedBits) {
1608 Diag(Arg->getSourceRange().getBegin(),
1609 diag::err_template_arg_too_large)
1610 << Value.toString(10) << Param->getType()
1611 << Arg->getSourceRange();
1612 Diag(Param->getLocation(), diag::note_template_param_here);
1613 return true;
1614 }
1615
1616 if (Value.getBitWidth() != AllowedBits)
1617 Value.extOrTrunc(AllowedBits);
1618 Value.setIsSigned(IntegerType->isSignedIntegerType());
1619 }
Douglas Gregorad964b32009-02-17 01:05:43 +00001620
Douglas Gregor8f378a92009-06-11 18:10:32 +00001621 // Add the value of this argument to the list of converted
1622 // arguments. We use the bitwidth and signedness of the template
1623 // parameter.
1624 if (Arg->isValueDependent()) {
1625 // The argument is value-dependent. Create a new
1626 // TemplateArgument with the converted expression.
1627 Converted = TemplateArgument(Arg);
1628 return false;
Douglas Gregorad964b32009-02-17 01:05:43 +00001629 }
1630
Douglas Gregor8f378a92009-06-11 18:10:32 +00001631 Converted = TemplateArgument(StartLoc, Value,
1632 ParamType->isEnumeralType() ? ParamType
1633 : IntegerType);
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001634 return false;
1635 }
Douglas Gregor2eedd992009-02-11 00:19:33 +00001636
Douglas Gregor3f411962009-02-11 01:18:59 +00001637 // Handle pointer-to-function, reference-to-function, and
1638 // pointer-to-member-function all in (roughly) the same way.
1639 if (// -- For a non-type template-parameter of type pointer to
1640 // function, only the function-to-pointer conversion (4.3) is
1641 // applied. If the template-argument represents a set of
1642 // overloaded functions (or a pointer to such), the matching
1643 // function is selected from the set (13.4).
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001644 // In C++0x, any std::nullptr_t value can be converted.
Douglas Gregor3f411962009-02-11 01:18:59 +00001645 (ParamType->isPointerType() &&
1646 ParamType->getAsPointerType()->getPointeeType()->isFunctionType()) ||
1647 // -- For a non-type template-parameter of type reference to
1648 // function, no conversions apply. If the template-argument
1649 // represents a set of overloaded functions, the matching
1650 // function is selected from the set (13.4).
1651 (ParamType->isReferenceType() &&
1652 ParamType->getAsReferenceType()->getPointeeType()->isFunctionType()) ||
1653 // -- For a non-type template-parameter of type pointer to
1654 // member function, no conversions apply. If the
1655 // template-argument represents a set of overloaded member
1656 // functions, the matching member function is selected from
1657 // the set (13.4).
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001658 // Again, C++0x allows a std::nullptr_t value.
Douglas Gregor3f411962009-02-11 01:18:59 +00001659 (ParamType->isMemberPointerType() &&
1660 ParamType->getAsMemberPointerType()->getPointeeType()
1661 ->isFunctionType())) {
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001662 if (Context.hasSameUnqualifiedType(ArgType,
1663 ParamType.getNonReferenceType())) {
Douglas Gregor2eedd992009-02-11 00:19:33 +00001664 // We don't have to do anything: the types already match.
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001665 } else if (ArgType->isNullPtrType() && (ParamType->isPointerType() ||
1666 ParamType->isMemberPointerType())) {
1667 ArgType = ParamType;
1668 ImpCastExprToType(Arg, ParamType);
Douglas Gregor3f411962009-02-11 01:18:59 +00001669 } else if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregor2eedd992009-02-11 00:19:33 +00001670 ArgType = Context.getPointerType(ArgType);
1671 ImpCastExprToType(Arg, ArgType);
1672 } else if (FunctionDecl *Fn
1673 = ResolveAddressOfOverloadedFunction(Arg, ParamType, true)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00001674 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
1675 return true;
1676
Douglas Gregor2eedd992009-02-11 00:19:33 +00001677 FixOverloadedFunctionReference(Arg, Fn);
1678 ArgType = Arg->getType();
Douglas Gregor3f411962009-02-11 01:18:59 +00001679 if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregor2eedd992009-02-11 00:19:33 +00001680 ArgType = Context.getPointerType(Arg->getType());
1681 ImpCastExprToType(Arg, ArgType);
1682 }
1683 }
1684
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001685 if (!Context.hasSameUnqualifiedType(ArgType,
1686 ParamType.getNonReferenceType())) {
Douglas Gregor2eedd992009-02-11 00:19:33 +00001687 // We can't perform this conversion.
1688 Diag(Arg->getSourceRange().getBegin(),
1689 diag::err_template_arg_not_convertible)
Douglas Gregored3a3982009-03-03 04:44:36 +00001690 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor2eedd992009-02-11 00:19:33 +00001691 Diag(Param->getLocation(), diag::note_template_param_here);
1692 return true;
1693 }
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001694
Douglas Gregorad964b32009-02-17 01:05:43 +00001695 if (ParamType->isMemberPointerType()) {
1696 NamedDecl *Member = 0;
1697 if (CheckTemplateArgumentPointerToMember(Arg, Member))
1698 return true;
1699
Douglas Gregor8f378a92009-06-11 18:10:32 +00001700 Member = cast_or_null<NamedDecl>(Context.getCanonicalDecl(Member));
1701 Converted = TemplateArgument(StartLoc, Member);
Douglas Gregorad964b32009-02-17 01:05:43 +00001702 return false;
1703 }
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001704
Douglas Gregorad964b32009-02-17 01:05:43 +00001705 NamedDecl *Entity = 0;
1706 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1707 return true;
1708
Douglas Gregor8f378a92009-06-11 18:10:32 +00001709 Entity = cast_or_null<NamedDecl>(Context.getCanonicalDecl(Entity));
1710 Converted = TemplateArgument(StartLoc, Entity);
Douglas Gregorad964b32009-02-17 01:05:43 +00001711 return false;
Douglas Gregor2eedd992009-02-11 00:19:33 +00001712 }
1713
Chris Lattner320dff22009-02-20 21:37:53 +00001714 if (ParamType->isPointerType()) {
Douglas Gregor3f411962009-02-11 01:18:59 +00001715 // -- for a non-type template-parameter of type pointer to
1716 // object, qualification conversions (4.4) and the
1717 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001718 // C++0x also allows a value of std::nullptr_t.
Douglas Gregor26ea1222009-03-24 20:32:41 +00001719 assert(ParamType->getAsPointerType()->getPointeeType()->isObjectType() &&
Douglas Gregor3f411962009-02-11 01:18:59 +00001720 "Only object pointers allowed here");
Douglas Gregord8c8c092009-02-11 00:44:29 +00001721
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001722 if (ArgType->isNullPtrType()) {
1723 ArgType = ParamType;
1724 ImpCastExprToType(Arg, ParamType);
1725 } else if (ArgType->isArrayType()) {
Douglas Gregor3f411962009-02-11 01:18:59 +00001726 ArgType = Context.getArrayDecayedType(ArgType);
1727 ImpCastExprToType(Arg, ArgType);
Douglas Gregord8c8c092009-02-11 00:44:29 +00001728 }
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001729
Douglas Gregor3f411962009-02-11 01:18:59 +00001730 if (IsQualificationConversion(ArgType, ParamType)) {
1731 ArgType = ParamType;
1732 ImpCastExprToType(Arg, ParamType);
1733 }
1734
Douglas Gregor0ea4e302009-02-11 18:22:40 +00001735 if (!Context.hasSameUnqualifiedType(ArgType, ParamType)) {
Douglas Gregor3f411962009-02-11 01:18:59 +00001736 // We can't perform this conversion.
1737 Diag(Arg->getSourceRange().getBegin(),
1738 diag::err_template_arg_not_convertible)
Douglas Gregored3a3982009-03-03 04:44:36 +00001739 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor3f411962009-02-11 01:18:59 +00001740 Diag(Param->getLocation(), diag::note_template_param_here);
1741 return true;
1742 }
1743
Douglas Gregorad964b32009-02-17 01:05:43 +00001744 NamedDecl *Entity = 0;
1745 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1746 return true;
1747
Douglas Gregor8f378a92009-06-11 18:10:32 +00001748 Entity = cast_or_null<NamedDecl>(Context.getCanonicalDecl(Entity));
1749 Converted = TemplateArgument(StartLoc, Entity);
Douglas Gregorad964b32009-02-17 01:05:43 +00001750 return false;
Douglas Gregord8c8c092009-02-11 00:44:29 +00001751 }
Douglas Gregor3f411962009-02-11 01:18:59 +00001752
1753 if (const ReferenceType *ParamRefType = ParamType->getAsReferenceType()) {
1754 // -- For a non-type template-parameter of type reference to
1755 // object, no conversions apply. The type referred to by the
1756 // reference may be more cv-qualified than the (otherwise
1757 // identical) type of the template-argument. The
1758 // template-parameter is bound directly to the
1759 // template-argument, which must be an lvalue.
Douglas Gregor26ea1222009-03-24 20:32:41 +00001760 assert(ParamRefType->getPointeeType()->isObjectType() &&
Douglas Gregor3f411962009-02-11 01:18:59 +00001761 "Only object references allowed here");
Douglas Gregord8c8c092009-02-11 00:44:29 +00001762
Douglas Gregor0ea4e302009-02-11 18:22:40 +00001763 if (!Context.hasSameUnqualifiedType(ParamRefType->getPointeeType(), ArgType)) {
Douglas Gregor3f411962009-02-11 01:18:59 +00001764 Diag(Arg->getSourceRange().getBegin(),
1765 diag::err_template_arg_no_ref_bind)
Douglas Gregored3a3982009-03-03 04:44:36 +00001766 << InstantiatedParamType << Arg->getType()
Douglas Gregor3f411962009-02-11 01:18:59 +00001767 << Arg->getSourceRange();
1768 Diag(Param->getLocation(), diag::note_template_param_here);
1769 return true;
1770 }
1771
1772 unsigned ParamQuals
1773 = Context.getCanonicalType(ParamType).getCVRQualifiers();
1774 unsigned ArgQuals = Context.getCanonicalType(ArgType).getCVRQualifiers();
1775
1776 if ((ParamQuals | ArgQuals) != ParamQuals) {
1777 Diag(Arg->getSourceRange().getBegin(),
1778 diag::err_template_arg_ref_bind_ignores_quals)
Douglas Gregored3a3982009-03-03 04:44:36 +00001779 << InstantiatedParamType << Arg->getType()
Douglas Gregor3f411962009-02-11 01:18:59 +00001780 << Arg->getSourceRange();
1781 Diag(Param->getLocation(), diag::note_template_param_here);
1782 return true;
1783 }
1784
Douglas Gregorad964b32009-02-17 01:05:43 +00001785 NamedDecl *Entity = 0;
1786 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1787 return true;
1788
Douglas Gregor8f378a92009-06-11 18:10:32 +00001789 Entity = cast<NamedDecl>(Context.getCanonicalDecl(Entity));
1790 Converted = TemplateArgument(StartLoc, Entity);
Douglas Gregorad964b32009-02-17 01:05:43 +00001791 return false;
Douglas Gregor3f411962009-02-11 01:18:59 +00001792 }
Douglas Gregor3628e1b2009-02-11 16:16:59 +00001793
1794 // -- For a non-type template-parameter of type pointer to data
1795 // member, qualification conversions (4.4) are applied.
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001796 // C++0x allows std::nullptr_t values.
Douglas Gregor3628e1b2009-02-11 16:16:59 +00001797 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
1798
Douglas Gregor0ea4e302009-02-11 18:22:40 +00001799 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
Douglas Gregor3628e1b2009-02-11 16:16:59 +00001800 // Types match exactly: nothing more to do here.
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001801 } else if (ArgType->isNullPtrType()) {
1802 ImpCastExprToType(Arg, ParamType);
Douglas Gregor3628e1b2009-02-11 16:16:59 +00001803 } else if (IsQualificationConversion(ArgType, ParamType)) {
1804 ImpCastExprToType(Arg, ParamType);
1805 } else {
1806 // We can't perform this conversion.
1807 Diag(Arg->getSourceRange().getBegin(),
1808 diag::err_template_arg_not_convertible)
Douglas Gregored3a3982009-03-03 04:44:36 +00001809 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor3628e1b2009-02-11 16:16:59 +00001810 Diag(Param->getLocation(), diag::note_template_param_here);
1811 return true;
1812 }
1813
Douglas Gregorad964b32009-02-17 01:05:43 +00001814 NamedDecl *Member = 0;
1815 if (CheckTemplateArgumentPointerToMember(Arg, Member))
1816 return true;
1817
Douglas Gregor8f378a92009-06-11 18:10:32 +00001818 Member = cast_or_null<NamedDecl>(Context.getCanonicalDecl(Member));
1819 Converted = TemplateArgument(StartLoc, Member);
Douglas Gregorad964b32009-02-17 01:05:43 +00001820 return false;
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001821}
1822
1823/// \brief Check a template argument against its corresponding
1824/// template template parameter.
1825///
1826/// This routine implements the semantics of C++ [temp.arg.template].
1827/// It returns true if an error occurred, and false otherwise.
1828bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
1829 DeclRefExpr *Arg) {
Douglas Gregore8e367f2009-02-10 00:24:35 +00001830 assert(isa<TemplateDecl>(Arg->getDecl()) && "Only template decls allowed");
1831 TemplateDecl *Template = cast<TemplateDecl>(Arg->getDecl());
1832
1833 // C++ [temp.arg.template]p1:
1834 // A template-argument for a template template-parameter shall be
1835 // the name of a class template, expressed as id-expression. Only
1836 // primary class templates are considered when matching the
1837 // template template argument with the corresponding parameter;
1838 // partial specializations are not considered even if their
1839 // parameter lists match that of the template template parameter.
Douglas Gregorfbcc9e92009-06-12 19:43:02 +00001840 //
1841 // Note that we also allow template template parameters here, which
1842 // will happen when we are dealing with, e.g., class template
1843 // partial specializations.
1844 if (!isa<ClassTemplateDecl>(Template) &&
1845 !isa<TemplateTemplateParmDecl>(Template)) {
Douglas Gregore8e367f2009-02-10 00:24:35 +00001846 assert(isa<FunctionTemplateDecl>(Template) &&
1847 "Only function templates are possible here");
Douglas Gregorb60eb752009-06-25 22:08:12 +00001848 Diag(Arg->getLocStart(), diag::err_template_arg_not_class_template);
1849 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
Douglas Gregore8e367f2009-02-10 00:24:35 +00001850 << Template;
1851 }
1852
1853 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
1854 Param->getTemplateParameters(),
1855 true, true,
1856 Arg->getSourceRange().getBegin());
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001857}
1858
Douglas Gregord406b032009-02-06 22:42:48 +00001859/// \brief Determine whether the given template parameter lists are
1860/// equivalent.
1861///
1862/// \param New The new template parameter list, typically written in the
1863/// source code as part of a new template declaration.
1864///
1865/// \param Old The old template parameter list, typically found via
1866/// name lookup of the template declared with this template parameter
1867/// list.
1868///
1869/// \param Complain If true, this routine will produce a diagnostic if
1870/// the template parameter lists are not equivalent.
1871///
Douglas Gregore8e367f2009-02-10 00:24:35 +00001872/// \param IsTemplateTemplateParm If true, this routine is being
1873/// called to compare the template parameter lists of a template
1874/// template parameter.
1875///
1876/// \param TemplateArgLoc If this source location is valid, then we
1877/// are actually checking the template parameter list of a template
1878/// argument (New) against the template parameter list of its
1879/// corresponding template template parameter (Old). We produce
1880/// slightly different diagnostics in this scenario.
1881///
Douglas Gregord406b032009-02-06 22:42:48 +00001882/// \returns True if the template parameter lists are equal, false
1883/// otherwise.
1884bool
1885Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
1886 TemplateParameterList *Old,
1887 bool Complain,
Douglas Gregore8e367f2009-02-10 00:24:35 +00001888 bool IsTemplateTemplateParm,
1889 SourceLocation TemplateArgLoc) {
Douglas Gregord406b032009-02-06 22:42:48 +00001890 if (Old->size() != New->size()) {
1891 if (Complain) {
Douglas Gregore8e367f2009-02-10 00:24:35 +00001892 unsigned NextDiag = diag::err_template_param_list_different_arity;
1893 if (TemplateArgLoc.isValid()) {
1894 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
1895 NextDiag = diag::note_template_param_list_different_arity;
1896 }
1897 Diag(New->getTemplateLoc(), NextDiag)
1898 << (New->size() > Old->size())
1899 << IsTemplateTemplateParm
1900 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
Douglas Gregord406b032009-02-06 22:42:48 +00001901 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
1902 << IsTemplateTemplateParm
1903 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
1904 }
1905
1906 return false;
1907 }
1908
1909 for (TemplateParameterList::iterator OldParm = Old->begin(),
1910 OldParmEnd = Old->end(), NewParm = New->begin();
1911 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
1912 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
Douglas Gregorbf6bc302009-06-24 16:50:40 +00001913 if (Complain) {
1914 unsigned NextDiag = diag::err_template_param_different_kind;
1915 if (TemplateArgLoc.isValid()) {
1916 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
1917 NextDiag = diag::note_template_param_different_kind;
1918 }
1919 Diag((*NewParm)->getLocation(), NextDiag)
1920 << IsTemplateTemplateParm;
1921 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
1922 << IsTemplateTemplateParm;
Douglas Gregore8e367f2009-02-10 00:24:35 +00001923 }
Douglas Gregord406b032009-02-06 22:42:48 +00001924 return false;
1925 }
1926
1927 if (isa<TemplateTypeParmDecl>(*OldParm)) {
1928 // Okay; all template type parameters are equivalent (since we
Douglas Gregore8e367f2009-02-10 00:24:35 +00001929 // know we're at the same index).
1930#if 0
Mike Stumpe127ae32009-05-16 07:39:55 +00001931 // FIXME: Enable this code in debug mode *after* we properly go through
1932 // and "instantiate" the template parameter lists of template template
1933 // parameters. It's only after this instantiation that (1) any dependent
1934 // types within the template parameter list of the template template
1935 // parameter can be checked, and (2) the template type parameter depths
Douglas Gregore8e367f2009-02-10 00:24:35 +00001936 // will match up.
Douglas Gregord406b032009-02-06 22:42:48 +00001937 QualType OldParmType
1938 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*OldParm));
1939 QualType NewParmType
1940 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*NewParm));
1941 assert(Context.getCanonicalType(OldParmType) ==
1942 Context.getCanonicalType(NewParmType) &&
1943 "type parameter mismatch?");
1944#endif
1945 } else if (NonTypeTemplateParmDecl *OldNTTP
1946 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
1947 // The types of non-type template parameters must agree.
1948 NonTypeTemplateParmDecl *NewNTTP
1949 = cast<NonTypeTemplateParmDecl>(*NewParm);
1950 if (Context.getCanonicalType(OldNTTP->getType()) !=
1951 Context.getCanonicalType(NewNTTP->getType())) {
1952 if (Complain) {
Douglas Gregore8e367f2009-02-10 00:24:35 +00001953 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
1954 if (TemplateArgLoc.isValid()) {
1955 Diag(TemplateArgLoc,
1956 diag::err_template_arg_template_params_mismatch);
1957 NextDiag = diag::note_template_nontype_parm_different_type;
1958 }
1959 Diag(NewNTTP->getLocation(), NextDiag)
Douglas Gregord406b032009-02-06 22:42:48 +00001960 << NewNTTP->getType()
1961 << IsTemplateTemplateParm;
1962 Diag(OldNTTP->getLocation(),
1963 diag::note_template_nontype_parm_prev_declaration)
1964 << OldNTTP->getType();
1965 }
1966 return false;
1967 }
1968 } else {
1969 // The template parameter lists of template template
1970 // parameters must agree.
1971 // FIXME: Could we perform a faster "type" comparison here?
1972 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
1973 "Only template template parameters handled here");
1974 TemplateTemplateParmDecl *OldTTP
1975 = cast<TemplateTemplateParmDecl>(*OldParm);
1976 TemplateTemplateParmDecl *NewTTP
1977 = cast<TemplateTemplateParmDecl>(*NewParm);
1978 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
1979 OldTTP->getTemplateParameters(),
1980 Complain,
Douglas Gregore8e367f2009-02-10 00:24:35 +00001981 /*IsTemplateTemplateParm=*/true,
1982 TemplateArgLoc))
Douglas Gregord406b032009-02-06 22:42:48 +00001983 return false;
1984 }
1985 }
1986
1987 return true;
1988}
1989
1990/// \brief Check whether a template can be declared within this scope.
1991///
1992/// If the template declaration is valid in this scope, returns
1993/// false. Otherwise, issues a diagnostic and returns true.
1994bool
1995Sema::CheckTemplateDeclScope(Scope *S,
1996 MultiTemplateParamsArg &TemplateParameterLists) {
1997 assert(TemplateParameterLists.size() > 0 && "Not a template");
1998
1999 // Find the nearest enclosing declaration scope.
2000 while ((S->getFlags() & Scope::DeclScope) == 0 ||
2001 (S->getFlags() & Scope::TemplateParamScope) != 0)
2002 S = S->getParent();
2003
2004 TemplateParameterList *TemplateParams =
2005 static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
2006 SourceLocation TemplateLoc = TemplateParams->getTemplateLoc();
2007 SourceRange TemplateRange
2008 = SourceRange(TemplateLoc, TemplateParams->getRAngleLoc());
2009
2010 // C++ [temp]p2:
2011 // A template-declaration can appear only as a namespace scope or
2012 // class scope declaration.
2013 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
2014 while (Ctx && isa<LinkageSpecDecl>(Ctx)) {
2015 if (cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
2016 return Diag(TemplateLoc, diag::err_template_linkage)
2017 << TemplateRange;
2018
2019 Ctx = Ctx->getParent();
2020 }
2021
2022 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
2023 return false;
2024
2025 return Diag(TemplateLoc, diag::err_template_outside_namespace_or_class_scope)
2026 << TemplateRange;
2027}
Douglas Gregora08b6c72009-02-17 23:15:12 +00002028
Douglas Gregor90177912009-05-13 18:28:20 +00002029/// \brief Check whether a class template specialization or explicit
2030/// instantiation in the current context is well-formed.
Douglas Gregor0d93f692009-02-25 22:02:03 +00002031///
Douglas Gregor90177912009-05-13 18:28:20 +00002032/// This routine determines whether a class template specialization or
2033/// explicit instantiation can be declared in the current context
2034/// (C++ [temp.expl.spec]p2, C++0x [temp.explicit]p2) and emits
2035/// appropriate diagnostics if there was an error. It returns true if
2036// there was an error that we cannot recover from, and false otherwise.
Douglas Gregor0d93f692009-02-25 22:02:03 +00002037bool
2038Sema::CheckClassTemplateSpecializationScope(ClassTemplateDecl *ClassTemplate,
2039 ClassTemplateSpecializationDecl *PrevDecl,
2040 SourceLocation TemplateNameLoc,
Douglas Gregor90177912009-05-13 18:28:20 +00002041 SourceRange ScopeSpecifierRange,
Douglas Gregor4faa4262009-06-12 22:21:45 +00002042 bool PartialSpecialization,
Douglas Gregor90177912009-05-13 18:28:20 +00002043 bool ExplicitInstantiation) {
Douglas Gregor0d93f692009-02-25 22:02:03 +00002044 // C++ [temp.expl.spec]p2:
2045 // An explicit specialization shall be declared in the namespace
2046 // of which the template is a member, or, for member templates, in
2047 // the namespace of which the enclosing class or enclosing class
2048 // template is a member. An explicit specialization of a member
2049 // function, member class or static data member of a class
2050 // template shall be declared in the namespace of which the class
2051 // template is a member. Such a declaration may also be a
2052 // definition. If the declaration is not a definition, the
2053 // specialization may be defined later in the name- space in which
2054 // the explicit specialization was declared, or in a namespace
2055 // that encloses the one in which the explicit specialization was
2056 // declared.
2057 if (CurContext->getLookupContext()->isFunctionOrMethod()) {
Douglas Gregor4faa4262009-06-12 22:21:45 +00002058 int Kind = ExplicitInstantiation? 2 : PartialSpecialization? 1 : 0;
Douglas Gregor0d93f692009-02-25 22:02:03 +00002059 Diag(TemplateNameLoc, diag::err_template_spec_decl_function_scope)
Douglas Gregor4faa4262009-06-12 22:21:45 +00002060 << Kind << ClassTemplate;
Douglas Gregor0d93f692009-02-25 22:02:03 +00002061 return true;
2062 }
2063
2064 DeclContext *DC = CurContext->getEnclosingNamespaceContext();
2065 DeclContext *TemplateContext
2066 = ClassTemplate->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregor90177912009-05-13 18:28:20 +00002067 if ((!PrevDecl || PrevDecl->getSpecializationKind() == TSK_Undeclared) &&
2068 !ExplicitInstantiation) {
Douglas Gregor0d93f692009-02-25 22:02:03 +00002069 // There is no prior declaration of this entity, so this
2070 // specialization must be in the same context as the template
2071 // itself.
2072 if (DC != TemplateContext) {
2073 if (isa<TranslationUnitDecl>(TemplateContext))
2074 Diag(TemplateNameLoc, diag::err_template_spec_decl_out_of_scope_global)
Douglas Gregor4faa4262009-06-12 22:21:45 +00002075 << PartialSpecialization
Douglas Gregor0d93f692009-02-25 22:02:03 +00002076 << ClassTemplate << ScopeSpecifierRange;
2077 else if (isa<NamespaceDecl>(TemplateContext))
2078 Diag(TemplateNameLoc, diag::err_template_spec_decl_out_of_scope)
Douglas Gregor4faa4262009-06-12 22:21:45 +00002079 << PartialSpecialization << ClassTemplate
2080 << cast<NamedDecl>(TemplateContext) << ScopeSpecifierRange;
Douglas Gregor0d93f692009-02-25 22:02:03 +00002081
2082 Diag(ClassTemplate->getLocation(), diag::note_template_decl_here);
2083 }
2084
2085 return false;
2086 }
2087
2088 // We have a previous declaration of this entity. Make sure that
2089 // this redeclaration (or definition) occurs in an enclosing namespace.
2090 if (!CurContext->Encloses(TemplateContext)) {
Mike Stumpe127ae32009-05-16 07:39:55 +00002091 // FIXME: In C++98, we would like to turn these errors into warnings,
2092 // dependent on a -Wc++0x flag.
Douglas Gregor90177912009-05-13 18:28:20 +00002093 bool SuppressedDiag = false;
Douglas Gregor4faa4262009-06-12 22:21:45 +00002094 int Kind = ExplicitInstantiation? 2 : PartialSpecialization? 1 : 0;
Douglas Gregor90177912009-05-13 18:28:20 +00002095 if (isa<TranslationUnitDecl>(TemplateContext)) {
2096 if (!ExplicitInstantiation || getLangOptions().CPlusPlus0x)
2097 Diag(TemplateNameLoc, diag::err_template_spec_redecl_global_scope)
Douglas Gregor4faa4262009-06-12 22:21:45 +00002098 << Kind << ClassTemplate << ScopeSpecifierRange;
Douglas Gregor90177912009-05-13 18:28:20 +00002099 else
2100 SuppressedDiag = true;
2101 } else if (isa<NamespaceDecl>(TemplateContext)) {
2102 if (!ExplicitInstantiation || getLangOptions().CPlusPlus0x)
2103 Diag(TemplateNameLoc, diag::err_template_spec_redecl_out_of_scope)
Douglas Gregor4faa4262009-06-12 22:21:45 +00002104 << Kind << ClassTemplate
Douglas Gregor90177912009-05-13 18:28:20 +00002105 << cast<NamedDecl>(TemplateContext) << ScopeSpecifierRange;
2106 else
2107 SuppressedDiag = true;
2108 }
Douglas Gregor0d93f692009-02-25 22:02:03 +00002109
Douglas Gregor90177912009-05-13 18:28:20 +00002110 if (!SuppressedDiag)
2111 Diag(ClassTemplate->getLocation(), diag::note_template_decl_here);
Douglas Gregor0d93f692009-02-25 22:02:03 +00002112 }
2113
2114 return false;
2115}
2116
Douglas Gregor76e79952009-06-12 21:21:02 +00002117/// \brief Check the non-type template arguments of a class template
2118/// partial specialization according to C++ [temp.class.spec]p9.
2119///
Douglas Gregor42476442009-06-12 22:08:06 +00002120/// \param TemplateParams the template parameters of the primary class
2121/// template.
2122///
2123/// \param TemplateArg the template arguments of the class template
2124/// partial specialization.
2125///
2126/// \param MirrorsPrimaryTemplate will be set true if the class
2127/// template partial specialization arguments are identical to the
2128/// implicit template arguments of the primary template. This is not
2129/// necessarily an error (C++0x), and it is left to the caller to diagnose
2130/// this condition when it is an error.
2131///
Douglas Gregor76e79952009-06-12 21:21:02 +00002132/// \returns true if there was an error, false otherwise.
2133bool Sema::CheckClassTemplatePartialSpecializationArgs(
2134 TemplateParameterList *TemplateParams,
Anders Carlsson13fac3f2009-06-13 18:20:51 +00002135 const TemplateArgumentListBuilder &TemplateArgs,
Douglas Gregor42476442009-06-12 22:08:06 +00002136 bool &MirrorsPrimaryTemplate) {
Douglas Gregor76e79952009-06-12 21:21:02 +00002137 // FIXME: the interface to this function will have to change to
2138 // accommodate variadic templates.
Douglas Gregor42476442009-06-12 22:08:06 +00002139 MirrorsPrimaryTemplate = true;
Anders Carlsson13fac3f2009-06-13 18:20:51 +00002140
Anders Carlssonb0fc9992009-06-23 01:26:57 +00002141 const TemplateArgument *ArgList = TemplateArgs.getFlatArguments();
Anders Carlsson13fac3f2009-06-13 18:20:51 +00002142
Douglas Gregor76e79952009-06-12 21:21:02 +00002143 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
Douglas Gregor42476442009-06-12 22:08:06 +00002144 // Determine whether the template argument list of the partial
2145 // specialization is identical to the implicit argument list of
2146 // the primary template. The caller may need to diagnostic this as
2147 // an error per C++ [temp.class.spec]p9b3.
2148 if (MirrorsPrimaryTemplate) {
2149 if (TemplateTypeParmDecl *TTP
2150 = dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(I))) {
2151 if (Context.getCanonicalType(Context.getTypeDeclType(TTP)) !=
Anders Carlsson13fac3f2009-06-13 18:20:51 +00002152 Context.getCanonicalType(ArgList[I].getAsType()))
Douglas Gregor42476442009-06-12 22:08:06 +00002153 MirrorsPrimaryTemplate = false;
2154 } else if (TemplateTemplateParmDecl *TTP
2155 = dyn_cast<TemplateTemplateParmDecl>(
2156 TemplateParams->getParam(I))) {
2157 // FIXME: We should settle on either Declaration storage or
2158 // Expression storage for template template parameters.
2159 TemplateTemplateParmDecl *ArgDecl
2160 = dyn_cast_or_null<TemplateTemplateParmDecl>(
Anders Carlsson13fac3f2009-06-13 18:20:51 +00002161 ArgList[I].getAsDecl());
Douglas Gregor42476442009-06-12 22:08:06 +00002162 if (!ArgDecl)
2163 if (DeclRefExpr *DRE
Anders Carlsson13fac3f2009-06-13 18:20:51 +00002164 = dyn_cast_or_null<DeclRefExpr>(ArgList[I].getAsExpr()))
Douglas Gregor42476442009-06-12 22:08:06 +00002165 ArgDecl = dyn_cast<TemplateTemplateParmDecl>(DRE->getDecl());
2166
2167 if (!ArgDecl ||
2168 ArgDecl->getIndex() != TTP->getIndex() ||
2169 ArgDecl->getDepth() != TTP->getDepth())
2170 MirrorsPrimaryTemplate = false;
2171 }
2172 }
2173
Douglas Gregor76e79952009-06-12 21:21:02 +00002174 NonTypeTemplateParmDecl *Param
2175 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
Douglas Gregor42476442009-06-12 22:08:06 +00002176 if (!Param) {
Douglas Gregor76e79952009-06-12 21:21:02 +00002177 continue;
Douglas Gregor42476442009-06-12 22:08:06 +00002178 }
2179
Anders Carlsson13fac3f2009-06-13 18:20:51 +00002180 Expr *ArgExpr = ArgList[I].getAsExpr();
Douglas Gregor42476442009-06-12 22:08:06 +00002181 if (!ArgExpr) {
2182 MirrorsPrimaryTemplate = false;
Douglas Gregor76e79952009-06-12 21:21:02 +00002183 continue;
Douglas Gregor42476442009-06-12 22:08:06 +00002184 }
Douglas Gregor76e79952009-06-12 21:21:02 +00002185
2186 // C++ [temp.class.spec]p8:
2187 // A non-type argument is non-specialized if it is the name of a
2188 // non-type parameter. All other non-type arguments are
2189 // specialized.
2190 //
2191 // Below, we check the two conditions that only apply to
2192 // specialized non-type arguments, so skip any non-specialized
2193 // arguments.
2194 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Douglas Gregor42476442009-06-12 22:08:06 +00002195 if (NonTypeTemplateParmDecl *NTTP
2196 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl())) {
2197 if (MirrorsPrimaryTemplate &&
2198 (Param->getIndex() != NTTP->getIndex() ||
2199 Param->getDepth() != NTTP->getDepth()))
2200 MirrorsPrimaryTemplate = false;
2201
Douglas Gregor76e79952009-06-12 21:21:02 +00002202 continue;
Douglas Gregor42476442009-06-12 22:08:06 +00002203 }
Douglas Gregor76e79952009-06-12 21:21:02 +00002204
2205 // C++ [temp.class.spec]p9:
2206 // Within the argument list of a class template partial
2207 // specialization, the following restrictions apply:
2208 // -- A partially specialized non-type argument expression
2209 // shall not involve a template parameter of the partial
2210 // specialization except when the argument expression is a
2211 // simple identifier.
2212 if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
2213 Diag(ArgExpr->getLocStart(),
2214 diag::err_dependent_non_type_arg_in_partial_spec)
2215 << ArgExpr->getSourceRange();
2216 return true;
2217 }
2218
2219 // -- The type of a template parameter corresponding to a
2220 // specialized non-type argument shall not be dependent on a
2221 // parameter of the specialization.
2222 if (Param->getType()->isDependentType()) {
2223 Diag(ArgExpr->getLocStart(),
2224 diag::err_dependent_typed_non_type_arg_in_partial_spec)
2225 << Param->getType()
2226 << ArgExpr->getSourceRange();
2227 Diag(Param->getLocation(), diag::note_template_param_here);
2228 return true;
2229 }
Douglas Gregor42476442009-06-12 22:08:06 +00002230
2231 MirrorsPrimaryTemplate = false;
Douglas Gregor76e79952009-06-12 21:21:02 +00002232 }
2233
2234 return false;
2235}
2236
Douglas Gregorc5d6fa72009-03-25 00:13:59 +00002237Sema::DeclResult
Douglas Gregora08b6c72009-02-17 23:15:12 +00002238Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec, TagKind TK,
2239 SourceLocation KWLoc,
2240 const CXXScopeSpec &SS,
Douglas Gregordd13e842009-03-30 22:58:21 +00002241 TemplateTy TemplateD,
Douglas Gregora08b6c72009-02-17 23:15:12 +00002242 SourceLocation TemplateNameLoc,
2243 SourceLocation LAngleLoc,
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00002244 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregora08b6c72009-02-17 23:15:12 +00002245 SourceLocation *TemplateArgLocs,
2246 SourceLocation RAngleLoc,
2247 AttributeList *Attr,
2248 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregora08b6c72009-02-17 23:15:12 +00002249 // Find the class template we're specializing
Douglas Gregordd13e842009-03-30 22:58:21 +00002250 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Douglas Gregora08b6c72009-02-17 23:15:12 +00002251 ClassTemplateDecl *ClassTemplate
Douglas Gregordd13e842009-03-30 22:58:21 +00002252 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
Douglas Gregora08b6c72009-02-17 23:15:12 +00002253
Douglas Gregor58944ac2009-05-31 09:31:02 +00002254 bool isPartialSpecialization = false;
2255
Douglas Gregor0d93f692009-02-25 22:02:03 +00002256 // Check the validity of the template headers that introduce this
2257 // template.
Douglas Gregor50113ca2009-02-25 22:18:32 +00002258 // FIXME: Once we have member templates, we'll need to check
2259 // C++ [temp.expl.spec]p17-18, where we could have multiple levels of
2260 // template<> headers.
Douglas Gregor3bb30002009-02-26 21:00:50 +00002261 if (TemplateParameterLists.size() == 0)
2262 Diag(KWLoc, diag::err_template_spec_needs_header)
Douglas Gregor61be3602009-02-27 17:53:17 +00002263 << CodeModificationHint::CreateInsertion(KWLoc, "template<> ");
Douglas Gregor3bb30002009-02-26 21:00:50 +00002264 else {
Douglas Gregor0d93f692009-02-25 22:02:03 +00002265 TemplateParameterList *TemplateParams
2266 = static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
Chris Lattner5261d0c2009-03-28 19:18:32 +00002267 if (TemplateParameterLists.size() > 1) {
2268 Diag(TemplateParams->getTemplateLoc(),
2269 diag::err_template_spec_extra_headers);
2270 return true;
2271 }
Douglas Gregor0d93f692009-02-25 22:02:03 +00002272
Douglas Gregorfbcc9e92009-06-12 19:43:02 +00002273 if (TemplateParams->size() > 0) {
Douglas Gregor58944ac2009-05-31 09:31:02 +00002274 isPartialSpecialization = true;
Douglas Gregorfbcc9e92009-06-12 19:43:02 +00002275
2276 // C++ [temp.class.spec]p10:
2277 // The template parameter list of a specialization shall not
2278 // contain default template argument values.
2279 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
2280 Decl *Param = TemplateParams->getParam(I);
2281 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
2282 if (TTP->hasDefaultArgument()) {
2283 Diag(TTP->getDefaultArgumentLoc(),
2284 diag::err_default_arg_in_partial_spec);
2285 TTP->setDefaultArgument(QualType(), SourceLocation(), false);
2286 }
2287 } else if (NonTypeTemplateParmDecl *NTTP
2288 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2289 if (Expr *DefArg = NTTP->getDefaultArgument()) {
2290 Diag(NTTP->getDefaultArgumentLoc(),
2291 diag::err_default_arg_in_partial_spec)
2292 << DefArg->getSourceRange();
2293 NTTP->setDefaultArgument(0);
2294 DefArg->Destroy(Context);
2295 }
2296 } else {
2297 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
2298 if (Expr *DefArg = TTP->getDefaultArgument()) {
2299 Diag(TTP->getDefaultArgumentLoc(),
2300 diag::err_default_arg_in_partial_spec)
2301 << DefArg->getSourceRange();
2302 TTP->setDefaultArgument(0);
2303 DefArg->Destroy(Context);
2304 }
2305 }
2306 }
2307 }
Douglas Gregor0d93f692009-02-25 22:02:03 +00002308 }
2309
Douglas Gregora08b6c72009-02-17 23:15:12 +00002310 // Check that the specialization uses the same tag kind as the
2311 // original template.
2312 TagDecl::TagKind Kind;
2313 switch (TagSpec) {
2314 default: assert(0 && "Unknown tag type!");
2315 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2316 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2317 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2318 }
Douglas Gregor625185c2009-05-14 16:41:31 +00002319 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
2320 Kind, KWLoc,
2321 *ClassTemplate->getIdentifier())) {
Douglas Gregor3faaa812009-04-01 23:51:29 +00002322 Diag(KWLoc, diag::err_use_with_wrong_tag)
2323 << ClassTemplate
2324 << CodeModificationHint::CreateReplacement(KWLoc,
2325 ClassTemplate->getTemplatedDecl()->getKindName());
Douglas Gregora08b6c72009-02-17 23:15:12 +00002326 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
2327 diag::note_previous_use);
2328 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
2329 }
2330
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00002331 // Translate the parser's template argument list in our AST format.
2332 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
2333 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
2334
Douglas Gregora08b6c72009-02-17 23:15:12 +00002335 // Check that the template argument list is well-formed for this
2336 // template.
Anders Carlssonb0fc9992009-06-23 01:26:57 +00002337 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
2338 TemplateArgs.size());
Douglas Gregora08b6c72009-02-17 23:15:12 +00002339 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
Anders Carlsson13fac3f2009-06-13 18:20:51 +00002340 TemplateArgs.data(), TemplateArgs.size(),
Anders Carlssonb0fc9992009-06-23 01:26:57 +00002341 RAngleLoc, Converted))
Douglas Gregorc5d6fa72009-03-25 00:13:59 +00002342 return true;
Douglas Gregora08b6c72009-02-17 23:15:12 +00002343
Anders Carlssonb0fc9992009-06-23 01:26:57 +00002344 assert((Converted.structuredSize() ==
Douglas Gregora08b6c72009-02-17 23:15:12 +00002345 ClassTemplate->getTemplateParameters()->size()) &&
2346 "Converted template argument list is too short!");
2347
Douglas Gregor58944ac2009-05-31 09:31:02 +00002348 // Find the class template (partial) specialization declaration that
Douglas Gregora08b6c72009-02-17 23:15:12 +00002349 // corresponds to these arguments.
2350 llvm::FoldingSetNodeID ID;
Douglas Gregorfbcc9e92009-06-12 19:43:02 +00002351 if (isPartialSpecialization) {
Douglas Gregor42476442009-06-12 22:08:06 +00002352 bool MirrorsPrimaryTemplate;
Douglas Gregor76e79952009-06-12 21:21:02 +00002353 if (CheckClassTemplatePartialSpecializationArgs(
2354 ClassTemplate->getTemplateParameters(),
Anders Carlssonb0fc9992009-06-23 01:26:57 +00002355 Converted, MirrorsPrimaryTemplate))
Douglas Gregor76e79952009-06-12 21:21:02 +00002356 return true;
2357
Douglas Gregor42476442009-06-12 22:08:06 +00002358 if (MirrorsPrimaryTemplate) {
2359 // C++ [temp.class.spec]p9b3:
2360 //
2361 // -- The argument list of the specialization shall not be identical
2362 // to the implicit argument list of the primary template.
2363 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
2364 << (TK == TK_Definition)
2365 << CodeModificationHint::CreateRemoval(SourceRange(LAngleLoc,
2366 RAngleLoc));
2367 return ActOnClassTemplate(S, TagSpec, TK, KWLoc, SS,
2368 ClassTemplate->getIdentifier(),
2369 TemplateNameLoc,
2370 Attr,
2371 move(TemplateParameterLists),
2372 AS_none);
2373 }
2374
Douglas Gregor58944ac2009-05-31 09:31:02 +00002375 // FIXME: Template parameter list matters, too
Anders Carlssona35faf92009-06-05 03:43:12 +00002376 ClassTemplatePartialSpecializationDecl::Profile(ID,
Anders Carlssonb0fc9992009-06-23 01:26:57 +00002377 Converted.getFlatArguments(),
2378 Converted.flatSize());
Douglas Gregorfbcc9e92009-06-12 19:43:02 +00002379 }
Douglas Gregor58944ac2009-05-31 09:31:02 +00002380 else
Anders Carlssona35faf92009-06-05 03:43:12 +00002381 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlssonb0fc9992009-06-23 01:26:57 +00002382 Converted.getFlatArguments(),
2383 Converted.flatSize());
Douglas Gregora08b6c72009-02-17 23:15:12 +00002384 void *InsertPos = 0;
Douglas Gregor58944ac2009-05-31 09:31:02 +00002385 ClassTemplateSpecializationDecl *PrevDecl = 0;
2386
2387 if (isPartialSpecialization)
2388 PrevDecl
2389 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
2390 InsertPos);
2391 else
2392 PrevDecl
2393 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregora08b6c72009-02-17 23:15:12 +00002394
2395 ClassTemplateSpecializationDecl *Specialization = 0;
2396
Douglas Gregor0d93f692009-02-25 22:02:03 +00002397 // Check whether we can declare a class template specialization in
2398 // the current scope.
2399 if (CheckClassTemplateSpecializationScope(ClassTemplate, PrevDecl,
2400 TemplateNameLoc,
Douglas Gregor90177912009-05-13 18:28:20 +00002401 SS.getRange(),
Douglas Gregor4faa4262009-06-12 22:21:45 +00002402 isPartialSpecialization,
Douglas Gregor90177912009-05-13 18:28:20 +00002403 /*ExplicitInstantiation=*/false))
Douglas Gregorc5d6fa72009-03-25 00:13:59 +00002404 return true;
Douglas Gregor0d93f692009-02-25 22:02:03 +00002405
Douglas Gregora08b6c72009-02-17 23:15:12 +00002406 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
2407 // Since the only prior class template specialization with these
2408 // arguments was referenced but not declared, reuse that
2409 // declaration node as our own, updating its source location to
2410 // reflect our new declaration.
Douglas Gregora08b6c72009-02-17 23:15:12 +00002411 Specialization = PrevDecl;
Douglas Gregor50113ca2009-02-25 22:18:32 +00002412 Specialization->setLocation(TemplateNameLoc);
Douglas Gregora08b6c72009-02-17 23:15:12 +00002413 PrevDecl = 0;
Douglas Gregor58944ac2009-05-31 09:31:02 +00002414 } else if (isPartialSpecialization) {
Douglas Gregor58944ac2009-05-31 09:31:02 +00002415 // Create a new class template partial specialization declaration node.
2416 TemplateParameterList *TemplateParams
2417 = static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
2418 ClassTemplatePartialSpecializationDecl *PrevPartial
2419 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
2420 ClassTemplatePartialSpecializationDecl *Partial
2421 = ClassTemplatePartialSpecializationDecl::Create(Context,
2422 ClassTemplate->getDeclContext(),
Anders Carlsson6e9d02f2009-06-05 04:06:48 +00002423 TemplateNameLoc,
2424 TemplateParams,
2425 ClassTemplate,
Anders Carlssonb0fc9992009-06-23 01:26:57 +00002426 Converted,
Anders Carlsson6e9d02f2009-06-05 04:06:48 +00002427 PrevPartial);
Douglas Gregor58944ac2009-05-31 09:31:02 +00002428
2429 if (PrevPartial) {
2430 ClassTemplate->getPartialSpecializations().RemoveNode(PrevPartial);
2431 ClassTemplate->getPartialSpecializations().GetOrInsertNode(Partial);
2432 } else {
2433 ClassTemplate->getPartialSpecializations().InsertNode(Partial, InsertPos);
2434 }
2435 Specialization = Partial;
Douglas Gregorf90c2132009-06-13 00:26:55 +00002436
2437 // Check that all of the template parameters of the class template
2438 // partial specialization are deducible from the template
2439 // arguments. If not, this class template partial specialization
2440 // will never be used.
2441 llvm::SmallVector<bool, 8> DeducibleParams;
2442 DeducibleParams.resize(TemplateParams->size());
2443 MarkDeducedTemplateParameters(Partial->getTemplateArgs(), DeducibleParams);
2444 unsigned NumNonDeducible = 0;
2445 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I)
2446 if (!DeducibleParams[I])
2447 ++NumNonDeducible;
2448
2449 if (NumNonDeducible) {
2450 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
2451 << (NumNonDeducible > 1)
2452 << SourceRange(TemplateNameLoc, RAngleLoc);
2453 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
2454 if (!DeducibleParams[I]) {
2455 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
2456 if (Param->getDeclName())
2457 Diag(Param->getLocation(),
2458 diag::note_partial_spec_unused_parameter)
2459 << Param->getDeclName();
2460 else
2461 Diag(Param->getLocation(),
2462 diag::note_partial_spec_unused_parameter)
2463 << std::string("<anonymous>");
2464 }
2465 }
2466 }
2467
Douglas Gregora08b6c72009-02-17 23:15:12 +00002468 } else {
2469 // Create a new class template specialization declaration node for
2470 // this explicit specialization.
2471 Specialization
2472 = ClassTemplateSpecializationDecl::Create(Context,
2473 ClassTemplate->getDeclContext(),
2474 TemplateNameLoc,
Anders Carlsson6e9d02f2009-06-05 04:06:48 +00002475 ClassTemplate,
Anders Carlssonb0fc9992009-06-23 01:26:57 +00002476 Converted,
Douglas Gregora08b6c72009-02-17 23:15:12 +00002477 PrevDecl);
2478
2479 if (PrevDecl) {
2480 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
2481 ClassTemplate->getSpecializations().GetOrInsertNode(Specialization);
2482 } else {
2483 ClassTemplate->getSpecializations().InsertNode(Specialization,
2484 InsertPos);
2485 }
2486 }
2487
2488 // Note that this is an explicit specialization.
2489 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
2490
2491 // Check that this isn't a redefinition of this specialization.
2492 if (TK == TK_Definition) {
2493 if (RecordDecl *Def = Specialization->getDefinition(Context)) {
Mike Stumpe127ae32009-05-16 07:39:55 +00002494 // FIXME: Should also handle explicit specialization after implicit
2495 // instantiation with a special diagnostic.
Douglas Gregora08b6c72009-02-17 23:15:12 +00002496 SourceRange Range(TemplateNameLoc, RAngleLoc);
2497 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregor58944ac2009-05-31 09:31:02 +00002498 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregora08b6c72009-02-17 23:15:12 +00002499 Diag(Def->getLocation(), diag::note_previous_definition);
2500 Specialization->setInvalidDecl();
Douglas Gregorc5d6fa72009-03-25 00:13:59 +00002501 return true;
Douglas Gregora08b6c72009-02-17 23:15:12 +00002502 }
2503 }
2504
Douglas Gregor9c7825b2009-02-26 22:19:44 +00002505 // Build the fully-sugared type for this class template
2506 // specialization as the user wrote in the specialization
2507 // itself. This means that we'll pretty-print the type retrieved
2508 // from the specialization's declaration the way that the user
2509 // actually wrote the specialization, rather than formatting the
2510 // name based on the "canonical" representation used to store the
2511 // template arguments in the specialization.
Douglas Gregor8c795a12009-03-19 00:39:20 +00002512 QualType WrittenTy
Douglas Gregordd13e842009-03-30 22:58:21 +00002513 = Context.getTemplateSpecializationType(Name,
Anders Carlsson13fac3f2009-06-13 18:20:51 +00002514 TemplateArgs.data(),
Douglas Gregordd13e842009-03-30 22:58:21 +00002515 TemplateArgs.size(),
Douglas Gregor8c795a12009-03-19 00:39:20 +00002516 Context.getTypeDeclType(Specialization));
Douglas Gregordd13e842009-03-30 22:58:21 +00002517 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00002518 TemplateArgsIn.release();
Douglas Gregora08b6c72009-02-17 23:15:12 +00002519
Douglas Gregor50113ca2009-02-25 22:18:32 +00002520 // C++ [temp.expl.spec]p9:
2521 // A template explicit specialization is in the scope of the
2522 // namespace in which the template was defined.
2523 //
2524 // We actually implement this paragraph where we set the semantic
2525 // context (in the creation of the ClassTemplateSpecializationDecl),
2526 // but we also maintain the lexical context where the actual
2527 // definition occurs.
Douglas Gregora08b6c72009-02-17 23:15:12 +00002528 Specialization->setLexicalDeclContext(CurContext);
2529
2530 // We may be starting the definition of this specialization.
2531 if (TK == TK_Definition)
2532 Specialization->startDefinition();
2533
2534 // Add the specialization into its lexical context, so that it can
2535 // be seen when iterating through the list of declarations in that
2536 // context. However, specializations are not found by name lookup.
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002537 CurContext->addDecl(Specialization);
Chris Lattner5261d0c2009-03-28 19:18:32 +00002538 return DeclPtrTy::make(Specialization);
Douglas Gregora08b6c72009-02-17 23:15:12 +00002539}
Douglas Gregord3022602009-03-27 23:10:48 +00002540
Douglas Gregor2ae1d772009-06-23 23:11:28 +00002541Sema::DeclPtrTy
2542Sema::ActOnTemplateDeclarator(Scope *S,
2543 MultiTemplateParamsArg TemplateParameterLists,
2544 Declarator &D) {
2545 return HandleDeclarator(S, D, move(TemplateParameterLists), false);
2546}
2547
Douglas Gregor19d10652009-06-24 00:54:41 +00002548Sema::DeclPtrTy
2549Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
2550 MultiTemplateParamsArg TemplateParameterLists,
2551 Declarator &D) {
2552 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
2553 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
2554 "Not a function declarator!");
2555 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2556
2557 if (FTI.hasPrototype) {
2558 // FIXME: Diagnose arguments without names in C.
2559 }
2560
2561 Scope *ParentScope = FnBodyScope->getParent();
2562
2563 DeclPtrTy DP = HandleDeclarator(ParentScope, D,
2564 move(TemplateParameterLists),
2565 /*IsFunctionDefinition=*/true);
Douglas Gregorb60eb752009-06-25 22:08:12 +00002566 FunctionTemplateDecl *FunctionTemplate
2567 = cast_or_null<FunctionTemplateDecl>(DP.getAs<Decl>());
2568 if (FunctionTemplate)
2569 return ActOnStartOfFunctionDef(FnBodyScope,
2570 DeclPtrTy::make(FunctionTemplate->getTemplatedDecl()));
2571
2572 return DeclPtrTy();
Douglas Gregor19d10652009-06-24 00:54:41 +00002573}
2574
Douglas Gregor96b6df92009-05-14 00:28:11 +00002575// Explicit instantiation of a class template specialization
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002576Sema::DeclResult
2577Sema::ActOnExplicitInstantiation(Scope *S, SourceLocation TemplateLoc,
2578 unsigned TagSpec,
2579 SourceLocation KWLoc,
2580 const CXXScopeSpec &SS,
2581 TemplateTy TemplateD,
2582 SourceLocation TemplateNameLoc,
2583 SourceLocation LAngleLoc,
2584 ASTTemplateArgsPtr TemplateArgsIn,
2585 SourceLocation *TemplateArgLocs,
2586 SourceLocation RAngleLoc,
2587 AttributeList *Attr) {
2588 // Find the class template we're specializing
2589 TemplateName Name = TemplateD.getAsVal<TemplateName>();
2590 ClassTemplateDecl *ClassTemplate
2591 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
2592
2593 // Check that the specialization uses the same tag kind as the
2594 // original template.
2595 TagDecl::TagKind Kind;
2596 switch (TagSpec) {
2597 default: assert(0 && "Unknown tag type!");
2598 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2599 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2600 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2601 }
Douglas Gregor625185c2009-05-14 16:41:31 +00002602 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
2603 Kind, KWLoc,
2604 *ClassTemplate->getIdentifier())) {
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002605 Diag(KWLoc, diag::err_use_with_wrong_tag)
2606 << ClassTemplate
2607 << CodeModificationHint::CreateReplacement(KWLoc,
2608 ClassTemplate->getTemplatedDecl()->getKindName());
2609 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
2610 diag::note_previous_use);
2611 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
2612 }
2613
Douglas Gregor90177912009-05-13 18:28:20 +00002614 // C++0x [temp.explicit]p2:
2615 // [...] An explicit instantiation shall appear in an enclosing
2616 // namespace of its template. [...]
2617 //
2618 // This is C++ DR 275.
2619 if (CheckClassTemplateSpecializationScope(ClassTemplate, 0,
2620 TemplateNameLoc,
2621 SS.getRange(),
Douglas Gregor4faa4262009-06-12 22:21:45 +00002622 /*PartialSpecialization=*/false,
Douglas Gregor90177912009-05-13 18:28:20 +00002623 /*ExplicitInstantiation=*/true))
2624 return true;
2625
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002626 // Translate the parser's template argument list in our AST format.
2627 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
2628 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
2629
2630 // Check that the template argument list is well-formed for this
2631 // template.
Anders Carlssonb0fc9992009-06-23 01:26:57 +00002632 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
2633 TemplateArgs.size());
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002634 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
Anders Carlssonb912b392009-06-05 02:12:32 +00002635 TemplateArgs.data(), TemplateArgs.size(),
Anders Carlssonb0fc9992009-06-23 01:26:57 +00002636 RAngleLoc, Converted))
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002637 return true;
2638
Anders Carlssonb0fc9992009-06-23 01:26:57 +00002639 assert((Converted.structuredSize() ==
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002640 ClassTemplate->getTemplateParameters()->size()) &&
2641 "Converted template argument list is too short!");
2642
2643 // Find the class template specialization declaration that
2644 // corresponds to these arguments.
2645 llvm::FoldingSetNodeID ID;
Anders Carlssona35faf92009-06-05 03:43:12 +00002646 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlssonb0fc9992009-06-23 01:26:57 +00002647 Converted.getFlatArguments(),
2648 Converted.flatSize());
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002649 void *InsertPos = 0;
2650 ClassTemplateSpecializationDecl *PrevDecl
2651 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
2652
2653 ClassTemplateSpecializationDecl *Specialization = 0;
2654
Douglas Gregor90177912009-05-13 18:28:20 +00002655 bool SpecializationRequiresInstantiation = true;
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002656 if (PrevDecl) {
Douglas Gregor90177912009-05-13 18:28:20 +00002657 if (PrevDecl->getSpecializationKind() == TSK_ExplicitInstantiation) {
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002658 // This particular specialization has already been declared or
2659 // instantiated. We cannot explicitly instantiate it.
Douglas Gregor90177912009-05-13 18:28:20 +00002660 Diag(TemplateNameLoc, diag::err_explicit_instantiation_duplicate)
2661 << Context.getTypeDeclType(PrevDecl);
2662 Diag(PrevDecl->getLocation(),
2663 diag::note_previous_explicit_instantiation);
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002664 return DeclPtrTy::make(PrevDecl);
2665 }
2666
Douglas Gregor90177912009-05-13 18:28:20 +00002667 if (PrevDecl->getSpecializationKind() == TSK_ExplicitSpecialization) {
Douglas Gregor96b6df92009-05-14 00:28:11 +00002668 // C++ DR 259, C++0x [temp.explicit]p4:
Douglas Gregor90177912009-05-13 18:28:20 +00002669 // For a given set of template parameters, if an explicit
2670 // instantiation of a template appears after a declaration of
2671 // an explicit specialization for that template, the explicit
2672 // instantiation has no effect.
2673 if (!getLangOptions().CPlusPlus0x) {
2674 Diag(TemplateNameLoc,
2675 diag::ext_explicit_instantiation_after_specialization)
2676 << Context.getTypeDeclType(PrevDecl);
2677 Diag(PrevDecl->getLocation(),
2678 diag::note_previous_template_specialization);
2679 }
2680
2681 // Create a new class template specialization declaration node
2682 // for this explicit specialization. This node is only used to
2683 // record the existence of this explicit instantiation for
2684 // accurate reproduction of the source code; we don't actually
2685 // use it for anything, since it is semantically irrelevant.
2686 Specialization
2687 = ClassTemplateSpecializationDecl::Create(Context,
2688 ClassTemplate->getDeclContext(),
2689 TemplateNameLoc,
2690 ClassTemplate,
Anders Carlssonb0fc9992009-06-23 01:26:57 +00002691 Converted, 0);
Douglas Gregor90177912009-05-13 18:28:20 +00002692 Specialization->setLexicalDeclContext(CurContext);
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002693 CurContext->addDecl(Specialization);
Douglas Gregor90177912009-05-13 18:28:20 +00002694 return DeclPtrTy::make(Specialization);
2695 }
2696
2697 // If we have already (implicitly) instantiated this
2698 // specialization, there is less work to do.
2699 if (PrevDecl->getSpecializationKind() == TSK_ImplicitInstantiation)
2700 SpecializationRequiresInstantiation = false;
2701
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002702 // Since the only prior class template specialization with these
2703 // arguments was referenced but not declared, reuse that
2704 // declaration node as our own, updating its source location to
2705 // reflect our new declaration.
2706 Specialization = PrevDecl;
2707 Specialization->setLocation(TemplateNameLoc);
2708 PrevDecl = 0;
2709 } else {
2710 // Create a new class template specialization declaration node for
2711 // this explicit specialization.
2712 Specialization
2713 = ClassTemplateSpecializationDecl::Create(Context,
2714 ClassTemplate->getDeclContext(),
2715 TemplateNameLoc,
2716 ClassTemplate,
Anders Carlssonb0fc9992009-06-23 01:26:57 +00002717 Converted, 0);
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002718
2719 ClassTemplate->getSpecializations().InsertNode(Specialization,
2720 InsertPos);
2721 }
2722
2723 // Build the fully-sugared type for this explicit instantiation as
2724 // the user wrote in the explicit instantiation itself. This means
2725 // that we'll pretty-print the type retrieved from the
2726 // specialization's declaration the way that the user actually wrote
2727 // the explicit instantiation, rather than formatting the name based
2728 // on the "canonical" representation used to store the template
2729 // arguments in the specialization.
2730 QualType WrittenTy
2731 = Context.getTemplateSpecializationType(Name,
Anders Carlssonefbff322009-06-05 02:45:24 +00002732 TemplateArgs.data(),
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002733 TemplateArgs.size(),
2734 Context.getTypeDeclType(Specialization));
2735 Specialization->setTypeAsWritten(WrittenTy);
2736 TemplateArgsIn.release();
2737
2738 // Add the explicit instantiation into its lexical context. However,
2739 // since explicit instantiations are never found by name lookup, we
2740 // just put it into the declaration context directly.
2741 Specialization->setLexicalDeclContext(CurContext);
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002742 CurContext->addDecl(Specialization);
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002743
2744 // C++ [temp.explicit]p3:
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002745 // A definition of a class template or class member template
2746 // shall be in scope at the point of the explicit instantiation of
2747 // the class template or class member template.
2748 //
2749 // This check comes when we actually try to perform the
2750 // instantiation.
Douglas Gregor556d8c72009-05-15 17:59:04 +00002751 if (SpecializationRequiresInstantiation)
2752 InstantiateClassTemplateSpecialization(Specialization, true);
Douglas Gregorb12249d2009-05-18 17:01:57 +00002753 else // Instantiate the members of this class template specialization.
Douglas Gregor556d8c72009-05-15 17:59:04 +00002754 InstantiateClassTemplateSpecializationMembers(TemplateLoc, Specialization);
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002755
2756 return DeclPtrTy::make(Specialization);
2757}
2758
Douglas Gregor96b6df92009-05-14 00:28:11 +00002759// Explicit instantiation of a member class of a class template.
2760Sema::DeclResult
2761Sema::ActOnExplicitInstantiation(Scope *S, SourceLocation TemplateLoc,
2762 unsigned TagSpec,
2763 SourceLocation KWLoc,
2764 const CXXScopeSpec &SS,
2765 IdentifierInfo *Name,
2766 SourceLocation NameLoc,
2767 AttributeList *Attr) {
2768
Douglas Gregor71f06032009-05-28 23:31:59 +00002769 bool Owned = false;
Douglas Gregor96b6df92009-05-14 00:28:11 +00002770 DeclPtrTy TagD = ActOnTag(S, TagSpec, Action::TK_Reference,
Douglas Gregor71f06032009-05-28 23:31:59 +00002771 KWLoc, SS, Name, NameLoc, Attr, AS_none, Owned);
Douglas Gregor96b6df92009-05-14 00:28:11 +00002772 if (!TagD)
2773 return true;
2774
2775 TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
2776 if (Tag->isEnum()) {
2777 Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
2778 << Context.getTypeDeclType(Tag);
2779 return true;
2780 }
2781
Douglas Gregord769bfa2009-05-27 17:30:49 +00002782 if (Tag->isInvalidDecl())
2783 return true;
2784
Douglas Gregor96b6df92009-05-14 00:28:11 +00002785 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
2786 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
2787 if (!Pattern) {
2788 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
2789 << Context.getTypeDeclType(Record);
2790 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
2791 return true;
2792 }
2793
2794 // C++0x [temp.explicit]p2:
2795 // [...] An explicit instantiation shall appear in an enclosing
2796 // namespace of its template. [...]
2797 //
2798 // This is C++ DR 275.
2799 if (getLangOptions().CPlusPlus0x) {
Mike Stumpe127ae32009-05-16 07:39:55 +00002800 // FIXME: In C++98, we would like to turn these errors into warnings,
2801 // dependent on a -Wc++0x flag.
Douglas Gregor96b6df92009-05-14 00:28:11 +00002802 DeclContext *PatternContext
2803 = Pattern->getDeclContext()->getEnclosingNamespaceContext();
2804 if (!CurContext->Encloses(PatternContext)) {
2805 Diag(TemplateLoc, diag::err_explicit_instantiation_out_of_scope)
2806 << Record << cast<NamedDecl>(PatternContext) << SS.getRange();
2807 Diag(Pattern->getLocation(), diag::note_previous_declaration);
2808 }
2809 }
2810
Douglas Gregor96b6df92009-05-14 00:28:11 +00002811 if (!Record->getDefinition(Context)) {
2812 // If the class has a definition, instantiate it (and all of its
2813 // members, recursively).
2814 Pattern = cast_or_null<CXXRecordDecl>(Pattern->getDefinition(Context));
2815 if (Pattern && InstantiateClass(TemplateLoc, Record, Pattern,
Douglas Gregor5f62c5e2009-05-14 23:26:13 +00002816 getTemplateInstantiationArgs(Record),
Douglas Gregor96b6df92009-05-14 00:28:11 +00002817 /*ExplicitInstantiation=*/true))
2818 return true;
Douglas Gregorb12249d2009-05-18 17:01:57 +00002819 } else // Instantiate all of the members of class.
Douglas Gregor96b6df92009-05-14 00:28:11 +00002820 InstantiateClassMembers(TemplateLoc, Record,
Douglas Gregor5f62c5e2009-05-14 23:26:13 +00002821 getTemplateInstantiationArgs(Record));
Douglas Gregor96b6df92009-05-14 00:28:11 +00002822
Mike Stumpe127ae32009-05-16 07:39:55 +00002823 // FIXME: We don't have any representation for explicit instantiations of
2824 // member classes. Such a representation is not needed for compilation, but it
2825 // should be available for clients that want to see all of the declarations in
2826 // the source code.
Douglas Gregor96b6df92009-05-14 00:28:11 +00002827 return TagD;
2828}
2829
Douglas Gregord3022602009-03-27 23:10:48 +00002830Sema::TypeResult
2831Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
2832 const IdentifierInfo &II, SourceLocation IdLoc) {
2833 NestedNameSpecifier *NNS
2834 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
2835 if (!NNS)
2836 return true;
2837
2838 QualType T = CheckTypenameType(NNS, II, SourceRange(TypenameLoc, IdLoc));
Douglas Gregord7cb0372009-04-01 21:51:26 +00002839 if (T.isNull())
2840 return true;
Douglas Gregord3022602009-03-27 23:10:48 +00002841 return T.getAsOpaquePtr();
2842}
2843
Douglas Gregor77da5802009-04-01 00:28:59 +00002844Sema::TypeResult
2845Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
2846 SourceLocation TemplateLoc, TypeTy *Ty) {
2847 QualType T = QualType::getFromOpaquePtr(Ty);
2848 NestedNameSpecifier *NNS
2849 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
2850 const TemplateSpecializationType *TemplateId
2851 = T->getAsTemplateSpecializationType();
2852 assert(TemplateId && "Expected a template specialization type");
2853
2854 if (NNS->isDependent())
2855 return Context.getTypenameType(NNS, TemplateId).getAsOpaquePtr();
2856
2857 return Context.getQualifiedNameType(NNS, T).getAsOpaquePtr();
2858}
2859
Douglas Gregord3022602009-03-27 23:10:48 +00002860/// \brief Build the type that describes a C++ typename specifier,
2861/// e.g., "typename T::type".
2862QualType
2863Sema::CheckTypenameType(NestedNameSpecifier *NNS, const IdentifierInfo &II,
2864 SourceRange Range) {
Douglas Gregor3eb20702009-05-11 19:58:34 +00002865 CXXRecordDecl *CurrentInstantiation = 0;
2866 if (NNS->isDependent()) {
2867 CurrentInstantiation = getCurrentInstantiationOf(NNS);
Douglas Gregord3022602009-03-27 23:10:48 +00002868
Douglas Gregor3eb20702009-05-11 19:58:34 +00002869 // If the nested-name-specifier does not refer to the current
2870 // instantiation, then build a typename type.
2871 if (!CurrentInstantiation)
2872 return Context.getTypenameType(NNS, &II);
2873 }
Douglas Gregord3022602009-03-27 23:10:48 +00002874
Douglas Gregor3eb20702009-05-11 19:58:34 +00002875 DeclContext *Ctx = 0;
2876
2877 if (CurrentInstantiation)
2878 Ctx = CurrentInstantiation;
2879 else {
2880 CXXScopeSpec SS;
2881 SS.setScopeRep(NNS);
2882 SS.setRange(Range);
2883 if (RequireCompleteDeclContext(SS))
2884 return QualType();
2885
2886 Ctx = computeDeclContext(SS);
2887 }
Douglas Gregord3022602009-03-27 23:10:48 +00002888 assert(Ctx && "No declaration context?");
2889
2890 DeclarationName Name(&II);
2891 LookupResult Result = LookupQualifiedName(Ctx, Name, LookupOrdinaryName,
2892 false);
2893 unsigned DiagID = 0;
2894 Decl *Referenced = 0;
2895 switch (Result.getKind()) {
2896 case LookupResult::NotFound:
2897 if (Ctx->isTranslationUnit())
2898 DiagID = diag::err_typename_nested_not_found_global;
2899 else
2900 DiagID = diag::err_typename_nested_not_found;
2901 break;
2902
2903 case LookupResult::Found:
2904 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getAsDecl())) {
2905 // We found a type. Build a QualifiedNameType, since the
2906 // typename-specifier was just sugar. FIXME: Tell
2907 // QualifiedNameType that it has a "typename" prefix.
2908 return Context.getQualifiedNameType(NNS, Context.getTypeDeclType(Type));
2909 }
2910
2911 DiagID = diag::err_typename_nested_not_type;
2912 Referenced = Result.getAsDecl();
2913 break;
2914
2915 case LookupResult::FoundOverloaded:
2916 DiagID = diag::err_typename_nested_not_type;
2917 Referenced = *Result.begin();
2918 break;
2919
2920 case LookupResult::AmbiguousBaseSubobjectTypes:
2921 case LookupResult::AmbiguousBaseSubobjects:
2922 case LookupResult::AmbiguousReference:
2923 DiagnoseAmbiguousLookup(Result, Name, Range.getEnd(), Range);
2924 return QualType();
2925 }
2926
2927 // If we get here, it's because name lookup did not find a
2928 // type. Emit an appropriate diagnostic and return an error.
2929 if (NamedDecl *NamedCtx = dyn_cast<NamedDecl>(Ctx))
2930 Diag(Range.getEnd(), DiagID) << Range << Name << NamedCtx;
2931 else
2932 Diag(Range.getEnd(), DiagID) << Range << Name;
2933 if (Referenced)
2934 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
2935 << Name;
2936 return QualType();
2937}