blob: d9c53ebec63d53d864850244dc39940dfb1fa0dc [file] [log] [blame]
Douglas Gregor72c3f312008-12-05 18:15:24 +00001//===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===/
Douglas Gregor72c3f312008-12-05 18:15:24 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Douglas Gregor99ebf652009-02-27 19:31:52 +00007//===----------------------------------------------------------------------===/
Douglas Gregor72c3f312008-12-05 18:15:24 +00008//
9// This file implements semantic analysis for C++ templates.
Douglas Gregor99ebf652009-02-27 19:31:52 +000010//===----------------------------------------------------------------------===/
Douglas Gregor72c3f312008-12-05 18:15:24 +000011
12#include "Sema.h"
Douglas Gregor4a959d82009-08-06 16:20:37 +000013#include "TreeTransform.h"
Douglas Gregorddc29e12009-02-06 22:42:48 +000014#include "clang/AST/ASTContext.h"
Douglas Gregor898574e2008-12-05 23:32:09 +000015#include "clang/AST/Expr.h"
Douglas Gregorcc45cb32009-02-11 19:52:55 +000016#include "clang/AST/ExprCXX.h"
Douglas Gregoraaba5e32009-02-04 19:02:06 +000017#include "clang/AST/DeclTemplate.h"
Douglas Gregor72c3f312008-12-05 18:15:24 +000018#include "clang/Parse/DeclSpec.h"
19#include "clang/Basic/LangOptions.h"
Douglas Gregord5a423b2009-09-25 18:43:00 +000020#include "clang/Basic/PartialDiagnostic.h"
Douglas Gregor4a959d82009-08-06 16:20:37 +000021#include "llvm/Support/Compiler.h"
Douglas Gregorbf4ea562009-09-15 16:23:51 +000022#include "llvm/ADT/StringExtras.h"
Douglas Gregor72c3f312008-12-05 18:15:24 +000023using namespace clang;
24
Douglas Gregor2dd078a2009-09-02 22:59:36 +000025/// \brief Determine whether the declaration found is acceptable as the name
26/// of a template and, if so, return that template declaration. Otherwise,
27/// returns NULL.
28static NamedDecl *isAcceptableTemplateName(ASTContext &Context, NamedDecl *D) {
29 if (!D)
30 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +000031
Douglas Gregor2dd078a2009-09-02 22:59:36 +000032 if (isa<TemplateDecl>(D))
33 return D;
Mike Stump1eb44332009-09-09 15:08:12 +000034
Douglas Gregor2dd078a2009-09-02 22:59:36 +000035 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
36 // C++ [temp.local]p1:
37 // Like normal (non-template) classes, class templates have an
38 // injected-class-name (Clause 9). The injected-class-name
39 // can be used with or without a template-argument-list. When
40 // it is used without a template-argument-list, it is
41 // equivalent to the injected-class-name followed by the
42 // template-parameters of the class template enclosed in
43 // <>. When it is used with a template-argument-list, it
44 // refers to the specified class template specialization,
45 // which could be the current specialization or another
46 // specialization.
47 if (Record->isInjectedClassName()) {
Douglas Gregor542b5482009-10-14 17:30:58 +000048 Record = cast<CXXRecordDecl>(Record->getDeclContext());
Douglas Gregor2dd078a2009-09-02 22:59:36 +000049 if (Record->getDescribedClassTemplate())
50 return Record->getDescribedClassTemplate();
51
52 if (ClassTemplateSpecializationDecl *Spec
53 = dyn_cast<ClassTemplateSpecializationDecl>(Record))
54 return Spec->getSpecializedTemplate();
55 }
Mike Stump1eb44332009-09-09 15:08:12 +000056
Douglas Gregor2dd078a2009-09-02 22:59:36 +000057 return 0;
58 }
Mike Stump1eb44332009-09-09 15:08:12 +000059
Douglas Gregor2dd078a2009-09-02 22:59:36 +000060 OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D);
61 if (!Ovl)
62 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +000063
Douglas Gregor2dd078a2009-09-02 22:59:36 +000064 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
65 FEnd = Ovl->function_end();
66 F != FEnd; ++F) {
67 if (FunctionTemplateDecl *FuncTmpl = dyn_cast<FunctionTemplateDecl>(*F)) {
68 // We've found a function template. Determine whether there are
69 // any other function templates we need to bundle together in an
70 // OverloadedFunctionDecl
71 for (++F; F != FEnd; ++F) {
72 if (isa<FunctionTemplateDecl>(*F))
73 break;
74 }
Mike Stump1eb44332009-09-09 15:08:12 +000075
Douglas Gregor2dd078a2009-09-02 22:59:36 +000076 if (F != FEnd) {
77 // Build an overloaded function decl containing only the
78 // function templates in Ovl.
Mike Stump1eb44332009-09-09 15:08:12 +000079 OverloadedFunctionDecl *OvlTemplate
Douglas Gregor2dd078a2009-09-02 22:59:36 +000080 = OverloadedFunctionDecl::Create(Context,
81 Ovl->getDeclContext(),
82 Ovl->getDeclName());
83 OvlTemplate->addOverload(FuncTmpl);
84 OvlTemplate->addOverload(*F);
85 for (++F; F != FEnd; ++F) {
86 if (isa<FunctionTemplateDecl>(*F))
87 OvlTemplate->addOverload(*F);
88 }
Mike Stump1eb44332009-09-09 15:08:12 +000089
Douglas Gregor2dd078a2009-09-02 22:59:36 +000090 return OvlTemplate;
91 }
92
93 return FuncTmpl;
94 }
95 }
Mike Stump1eb44332009-09-09 15:08:12 +000096
Douglas Gregor2dd078a2009-09-02 22:59:36 +000097 return 0;
98}
99
100TemplateNameKind Sema::isTemplateName(Scope *S,
Mike Stump1eb44332009-09-09 15:08:12 +0000101 const IdentifierInfo &II,
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000102 SourceLocation IdLoc,
Douglas Gregor495c35d2009-08-25 22:51:20 +0000103 const CXXScopeSpec *SS,
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000104 TypeTy *ObjectTypePtr,
Douglas Gregor495c35d2009-08-25 22:51:20 +0000105 bool EnteringContext,
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000106 TemplateTy &TemplateResult) {
107 // Determine where to perform name lookup
108 DeclContext *LookupCtx = 0;
109 bool isDependent = false;
110 if (ObjectTypePtr) {
111 // This nested-name-specifier occurs in a member access expression, e.g.,
112 // x->B::f, and we are looking into the type of the object.
Mike Stump1eb44332009-09-09 15:08:12 +0000113 assert((!SS || !SS->isSet()) &&
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000114 "ObjectType and scope specifier cannot coexist");
115 QualType ObjectType = QualType::getFromOpaquePtr(ObjectTypePtr);
116 LookupCtx = computeDeclContext(ObjectType);
117 isDependent = ObjectType->isDependentType();
118 } else if (SS && SS->isSet()) {
119 // This nested-name-specifier occurs after another nested-name-specifier,
120 // so long into the context associated with the prior nested-name-specifier.
121
122 LookupCtx = computeDeclContext(*SS, EnteringContext);
123 isDependent = isDependentScopeSpecifier(*SS);
124 }
Mike Stump1eb44332009-09-09 15:08:12 +0000125
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000126 LookupResult Found;
127 bool ObjectTypeSearchedInScope = false;
128 if (LookupCtx) {
129 // Perform "qualified" name lookup into the declaration context we
130 // computed, which is either the type of the base of a member access
Mike Stump1eb44332009-09-09 15:08:12 +0000131 // expression or the declaration context associated with a prior
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000132 // nested-name-specifier.
133
134 // The declaration context must be complete.
135 if (!LookupCtx->isDependentContext() && RequireCompleteDeclContext(*SS))
136 return TNK_Non_template;
Mike Stump1eb44332009-09-09 15:08:12 +0000137
John McCallf36e02d2009-10-09 21:13:30 +0000138 LookupQualifiedName(Found, LookupCtx, &II, LookupOrdinaryName);
Mike Stump1eb44332009-09-09 15:08:12 +0000139
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000140 if (ObjectTypePtr && Found.getKind() == LookupResult::NotFound) {
141 // C++ [basic.lookup.classref]p1:
142 // In a class member access expression (5.2.5), if the . or -> token is
Mike Stump1eb44332009-09-09 15:08:12 +0000143 // immediately followed by an identifier followed by a <, the
144 // identifier must be looked up to determine whether the < is the
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000145 // beginning of a template argument list (14.2) or a less-than operator.
Mike Stump1eb44332009-09-09 15:08:12 +0000146 // The identifier is first looked up in the class of the object
147 // expression. If the identifier is not found, it is then looked up in
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000148 // the context of the entire postfix-expression and shall name a class
149 // or function template.
150 //
151 // FIXME: When we're instantiating a template, do we actually have to
152 // look in the scope of the template? Seems fishy...
John McCallf36e02d2009-10-09 21:13:30 +0000153 LookupName(Found, S, &II, LookupOrdinaryName);
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000154 ObjectTypeSearchedInScope = true;
155 }
156 } else if (isDependent) {
Mike Stump1eb44332009-09-09 15:08:12 +0000157 // We cannot look into a dependent object type or
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000158 return TNK_Non_template;
159 } else {
160 // Perform unqualified name lookup in the current scope.
John McCallf36e02d2009-10-09 21:13:30 +0000161 LookupName(Found, S, &II, LookupOrdinaryName);
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000162 }
Mike Stump1eb44332009-09-09 15:08:12 +0000163
Douglas Gregor495c35d2009-08-25 22:51:20 +0000164 // FIXME: Cope with ambiguous name-lookup results.
Mike Stump1eb44332009-09-09 15:08:12 +0000165 assert(!Found.isAmbiguous() &&
Douglas Gregor495c35d2009-08-25 22:51:20 +0000166 "Cannot handle template name-lookup ambiguities");
Douglas Gregor7532dc62009-03-30 22:58:21 +0000167
John McCallf36e02d2009-10-09 21:13:30 +0000168 NamedDecl *Template
169 = isAcceptableTemplateName(Context, Found.getAsSingleDecl(Context));
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000170 if (!Template)
171 return TNK_Non_template;
172
173 if (ObjectTypePtr && !ObjectTypeSearchedInScope) {
174 // C++ [basic.lookup.classref]p1:
Mike Stump1eb44332009-09-09 15:08:12 +0000175 // [...] If the lookup in the class of the object expression finds a
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000176 // template, the name is also looked up in the context of the entire
177 // postfix-expression and [...]
178 //
John McCallf36e02d2009-10-09 21:13:30 +0000179 LookupResult FoundOuter;
180 LookupName(FoundOuter, S, &II, LookupOrdinaryName);
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000181 // FIXME: Handle ambiguities in this lookup better
John McCallf36e02d2009-10-09 21:13:30 +0000182 NamedDecl *OuterTemplate
183 = isAcceptableTemplateName(Context, FoundOuter.getAsSingleDecl(Context));
Mike Stump1eb44332009-09-09 15:08:12 +0000184
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000185 if (!OuterTemplate) {
Mike Stump1eb44332009-09-09 15:08:12 +0000186 // - if the name is not found, the name found in the class of the
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000187 // object expression is used, otherwise
188 } else if (!isa<ClassTemplateDecl>(OuterTemplate)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000189 // - if the name is found in the context of the entire
190 // postfix-expression and does not name a class template, the name
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000191 // found in the class of the object expression is used, otherwise
192 } else {
193 // - if the name found is a class template, it must refer to the same
Mike Stump1eb44332009-09-09 15:08:12 +0000194 // entity as the one found in the class of the object expression,
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000195 // otherwise the program is ill-formed.
196 if (OuterTemplate->getCanonicalDecl() != Template->getCanonicalDecl()) {
197 Diag(IdLoc, diag::err_nested_name_member_ref_lookup_ambiguous)
198 << &II;
199 Diag(Template->getLocation(), diag::note_ambig_member_ref_object_type)
200 << QualType::getFromOpaquePtr(ObjectTypePtr);
201 Diag(OuterTemplate->getLocation(), diag::note_ambig_member_ref_scope);
Mike Stump1eb44332009-09-09 15:08:12 +0000202
203 // Recover by taking the template that we found in the object
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000204 // expression's type.
Douglas Gregorbefc20e2009-03-26 00:10:35 +0000205 }
Mike Stump1eb44332009-09-09 15:08:12 +0000206 }
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000207 }
Mike Stump1eb44332009-09-09 15:08:12 +0000208
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000209 if (SS && SS->isSet() && !SS->isInvalid()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000210 NestedNameSpecifier *Qualifier
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000211 = static_cast<NestedNameSpecifier *>(SS->getScopeRep());
Mike Stump1eb44332009-09-09 15:08:12 +0000212 if (OverloadedFunctionDecl *Ovl
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000213 = dyn_cast<OverloadedFunctionDecl>(Template))
Mike Stump1eb44332009-09-09 15:08:12 +0000214 TemplateResult
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000215 = TemplateTy::make(Context.getQualifiedTemplateName(Qualifier, false,
216 Ovl));
217 else
Mike Stump1eb44332009-09-09 15:08:12 +0000218 TemplateResult
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000219 = TemplateTy::make(Context.getQualifiedTemplateName(Qualifier, false,
Mike Stump1eb44332009-09-09 15:08:12 +0000220 cast<TemplateDecl>(Template)));
221 } else if (OverloadedFunctionDecl *Ovl
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000222 = dyn_cast<OverloadedFunctionDecl>(Template)) {
223 TemplateResult = TemplateTy::make(TemplateName(Ovl));
224 } else {
225 TemplateResult = TemplateTy::make(
226 TemplateName(cast<TemplateDecl>(Template)));
227 }
Mike Stump1eb44332009-09-09 15:08:12 +0000228
229 if (isa<ClassTemplateDecl>(Template) ||
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000230 isa<TemplateTemplateParmDecl>(Template))
231 return TNK_Type_template;
Mike Stump1eb44332009-09-09 15:08:12 +0000232
233 assert((isa<FunctionTemplateDecl>(Template) ||
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000234 isa<OverloadedFunctionDecl>(Template)) &&
235 "Unhandled template kind in Sema::isTemplateName");
236 return TNK_Function_template;
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000237}
238
Douglas Gregor72c3f312008-12-05 18:15:24 +0000239/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
240/// that the template parameter 'PrevDecl' is being shadowed by a new
241/// declaration at location Loc. Returns true to indicate that this is
242/// an error, and false otherwise.
243bool Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
Douglas Gregorf57172b2008-12-08 18:40:42 +0000244 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregor72c3f312008-12-05 18:15:24 +0000245
246 // Microsoft Visual C++ permits template parameters to be shadowed.
247 if (getLangOptions().Microsoft)
248 return false;
249
250 // C++ [temp.local]p4:
251 // A template-parameter shall not be redeclared within its
252 // scope (including nested scopes).
Mike Stump1eb44332009-09-09 15:08:12 +0000253 Diag(Loc, diag::err_template_param_shadow)
Douglas Gregor72c3f312008-12-05 18:15:24 +0000254 << cast<NamedDecl>(PrevDecl)->getDeclName();
255 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
256 return true;
257}
258
Douglas Gregor2943aed2009-03-03 04:44:36 +0000259/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000260/// the parameter D to reference the templated declaration and return a pointer
261/// to the template declaration. Otherwise, do nothing to D and return null.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000262TemplateDecl *Sema::AdjustDeclIfTemplate(DeclPtrTy &D) {
Douglas Gregor13d2d6c2009-10-06 21:27:51 +0000263 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D.getAs<Decl>())) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000264 D = DeclPtrTy::make(Temp->getTemplatedDecl());
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000265 return Temp;
266 }
267 return 0;
268}
269
Douglas Gregor72c3f312008-12-05 18:15:24 +0000270/// ActOnTypeParameter - Called when a C++ template type parameter
271/// (e.g., "typename T") has been parsed. Typename specifies whether
272/// the keyword "typename" was used to declare the type parameter
273/// (otherwise, "class" was used), and KeyLoc is the location of the
274/// "class" or "typename" keyword. ParamName is the name of the
275/// parameter (NULL indicates an unnamed template parameter) and
Mike Stump1eb44332009-09-09 15:08:12 +0000276/// ParamName is the location of the parameter name (if any).
Douglas Gregor72c3f312008-12-05 18:15:24 +0000277/// If the type parameter has a default argument, it will be added
278/// later via ActOnTypeParameterDefault.
Mike Stump1eb44332009-09-09 15:08:12 +0000279Sema::DeclPtrTy Sema::ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis,
Anders Carlsson941df7d2009-06-12 19:58:00 +0000280 SourceLocation EllipsisLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +0000281 SourceLocation KeyLoc,
282 IdentifierInfo *ParamName,
283 SourceLocation ParamNameLoc,
284 unsigned Depth, unsigned Position) {
Mike Stump1eb44332009-09-09 15:08:12 +0000285 assert(S->isTemplateParamScope() &&
286 "Template type parameter not in template parameter scope!");
Douglas Gregor72c3f312008-12-05 18:15:24 +0000287 bool Invalid = false;
288
289 if (ParamName) {
John McCallf36e02d2009-10-09 21:13:30 +0000290 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, LookupTagName);
Douglas Gregorf57172b2008-12-08 18:40:42 +0000291 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor72c3f312008-12-05 18:15:24 +0000292 Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc,
Mike Stump1eb44332009-09-09 15:08:12 +0000293 PrevDecl);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000294 }
295
Douglas Gregorddc29e12009-02-06 22:42:48 +0000296 SourceLocation Loc = ParamNameLoc;
297 if (!ParamName)
298 Loc = KeyLoc;
299
Douglas Gregor72c3f312008-12-05 18:15:24 +0000300 TemplateTypeParmDecl *Param
Mike Stump1eb44332009-09-09 15:08:12 +0000301 = TemplateTypeParmDecl::Create(Context, CurContext, Loc,
302 Depth, Position, ParamName, Typename,
Anders Carlsson6d845ae2009-06-12 22:23:22 +0000303 Ellipsis);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000304 if (Invalid)
305 Param->setInvalidDecl();
306
307 if (ParamName) {
308 // Add the template parameter into the current scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000309 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor72c3f312008-12-05 18:15:24 +0000310 IdResolver.AddDecl(Param);
311 }
312
Chris Lattnerb28317a2009-03-28 19:18:32 +0000313 return DeclPtrTy::make(Param);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000314}
315
Douglas Gregord684b002009-02-10 19:49:53 +0000316/// ActOnTypeParameterDefault - Adds a default argument (the type
Mike Stump1eb44332009-09-09 15:08:12 +0000317/// Default) to the given template type parameter (TypeParam).
318void Sema::ActOnTypeParameterDefault(DeclPtrTy TypeParam,
Douglas Gregord684b002009-02-10 19:49:53 +0000319 SourceLocation EqualLoc,
Mike Stump1eb44332009-09-09 15:08:12 +0000320 SourceLocation DefaultLoc,
Douglas Gregord684b002009-02-10 19:49:53 +0000321 TypeTy *DefaultT) {
Mike Stump1eb44332009-09-09 15:08:12 +0000322 TemplateTypeParmDecl *Parm
Chris Lattnerb28317a2009-03-28 19:18:32 +0000323 = cast<TemplateTypeParmDecl>(TypeParam.getAs<Decl>());
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000324 // FIXME: Preserve type source info.
325 QualType Default = GetTypeFromParser(DefaultT);
Douglas Gregord684b002009-02-10 19:49:53 +0000326
Anders Carlsson9c4c5c82009-06-12 22:30:13 +0000327 // C++0x [temp.param]p9:
328 // A default template-argument may be specified for any kind of
Mike Stump1eb44332009-09-09 15:08:12 +0000329 // template-parameter that is not a template parameter pack.
Anders Carlsson9c4c5c82009-06-12 22:30:13 +0000330 if (Parm->isParameterPack()) {
331 Diag(DefaultLoc, diag::err_template_param_pack_default_arg);
Anders Carlsson9c4c5c82009-06-12 22:30:13 +0000332 return;
333 }
Mike Stump1eb44332009-09-09 15:08:12 +0000334
Douglas Gregord684b002009-02-10 19:49:53 +0000335 // C++ [temp.param]p14:
336 // A template-parameter shall not be used in its own default argument.
337 // FIXME: Implement this check! Needs a recursive walk over the types.
Mike Stump1eb44332009-09-09 15:08:12 +0000338
Douglas Gregord684b002009-02-10 19:49:53 +0000339 // Check the template argument itself.
340 if (CheckTemplateArgument(Parm, Default, DefaultLoc)) {
341 Parm->setInvalidDecl();
342 return;
343 }
344
345 Parm->setDefaultArgument(Default, DefaultLoc, false);
346}
347
Douglas Gregor2943aed2009-03-03 04:44:36 +0000348/// \brief Check that the type of a non-type template parameter is
349/// well-formed.
350///
351/// \returns the (possibly-promoted) parameter type if valid;
352/// otherwise, produces a diagnostic and returns a NULL type.
Mike Stump1eb44332009-09-09 15:08:12 +0000353QualType
Douglas Gregor2943aed2009-03-03 04:44:36 +0000354Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
355 // C++ [temp.param]p4:
356 //
357 // A non-type template-parameter shall have one of the following
358 // (optionally cv-qualified) types:
359 //
360 // -- integral or enumeration type,
361 if (T->isIntegralType() || T->isEnumeralType() ||
Mike Stump1eb44332009-09-09 15:08:12 +0000362 // -- pointer to object or pointer to function,
363 (T->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +0000364 (T->getAs<PointerType>()->getPointeeType()->isObjectType() ||
365 T->getAs<PointerType>()->getPointeeType()->isFunctionType())) ||
Mike Stump1eb44332009-09-09 15:08:12 +0000366 // -- reference to object or reference to function,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000367 T->isReferenceType() ||
368 // -- pointer to member.
369 T->isMemberPointerType() ||
370 // If T is a dependent type, we can't do the check now, so we
371 // assume that it is well-formed.
372 T->isDependentType())
373 return T;
374 // C++ [temp.param]p8:
375 //
376 // A non-type template-parameter of type "array of T" or
377 // "function returning T" is adjusted to be of type "pointer to
378 // T" or "pointer to function returning T", respectively.
379 else if (T->isArrayType())
380 // FIXME: Keep the type prior to promotion?
381 return Context.getArrayDecayedType(T);
382 else if (T->isFunctionType())
383 // FIXME: Keep the type prior to promotion?
384 return Context.getPointerType(T);
385
386 Diag(Loc, diag::err_template_nontype_parm_bad_type)
387 << T;
388
389 return QualType();
390}
391
Douglas Gregor72c3f312008-12-05 18:15:24 +0000392/// ActOnNonTypeTemplateParameter - Called when a C++ non-type
393/// template parameter (e.g., "int Size" in "template<int Size>
394/// class Array") has been parsed. S is the current scope and D is
395/// the parsed declarator.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000396Sema::DeclPtrTy Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
Mike Stump1eb44332009-09-09 15:08:12 +0000397 unsigned Depth,
Chris Lattnerb28317a2009-03-28 19:18:32 +0000398 unsigned Position) {
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000399 DeclaratorInfo *DInfo = 0;
400 QualType T = GetTypeForDeclarator(D, S, &DInfo);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000401
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000402 assert(S->isTemplateParamScope() &&
403 "Non-type template parameter not in template parameter scope!");
Douglas Gregor72c3f312008-12-05 18:15:24 +0000404 bool Invalid = false;
405
406 IdentifierInfo *ParamName = D.getIdentifier();
407 if (ParamName) {
John McCallf36e02d2009-10-09 21:13:30 +0000408 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, LookupTagName);
Douglas Gregorf57172b2008-12-08 18:40:42 +0000409 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor72c3f312008-12-05 18:15:24 +0000410 Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000411 PrevDecl);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000412 }
413
Douglas Gregor2943aed2009-03-03 04:44:36 +0000414 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
Douglas Gregorceef30c2009-03-09 16:46:39 +0000415 if (T.isNull()) {
Douglas Gregor2943aed2009-03-03 04:44:36 +0000416 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregorceef30c2009-03-09 16:46:39 +0000417 Invalid = true;
418 }
Douglas Gregor5d290d52009-02-10 17:43:50 +0000419
Douglas Gregor72c3f312008-12-05 18:15:24 +0000420 NonTypeTemplateParmDecl *Param
421 = NonTypeTemplateParmDecl::Create(Context, CurContext, D.getIdentifierLoc(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000422 Depth, Position, ParamName, T, DInfo);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000423 if (Invalid)
424 Param->setInvalidDecl();
425
426 if (D.getIdentifier()) {
427 // Add the template parameter into the current scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000428 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor72c3f312008-12-05 18:15:24 +0000429 IdResolver.AddDecl(Param);
430 }
Chris Lattnerb28317a2009-03-28 19:18:32 +0000431 return DeclPtrTy::make(Param);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000432}
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000433
Douglas Gregord684b002009-02-10 19:49:53 +0000434/// \brief Adds a default argument to the given non-type template
435/// parameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000436void Sema::ActOnNonTypeTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregord684b002009-02-10 19:49:53 +0000437 SourceLocation EqualLoc,
438 ExprArg DefaultE) {
Mike Stump1eb44332009-09-09 15:08:12 +0000439 NonTypeTemplateParmDecl *TemplateParm
Chris Lattnerb28317a2009-03-28 19:18:32 +0000440 = cast<NonTypeTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregord684b002009-02-10 19:49:53 +0000441 Expr *Default = static_cast<Expr *>(DefaultE.get());
Mike Stump1eb44332009-09-09 15:08:12 +0000442
Douglas Gregord684b002009-02-10 19:49:53 +0000443 // C++ [temp.param]p14:
444 // A template-parameter shall not be used in its own default argument.
445 // FIXME: Implement this check! Needs a recursive walk over the types.
Mike Stump1eb44332009-09-09 15:08:12 +0000446
Douglas Gregord684b002009-02-10 19:49:53 +0000447 // Check the well-formedness of the default template argument.
Douglas Gregor02cbbd22009-06-11 18:10:32 +0000448 TemplateArgument Converted;
449 if (CheckTemplateArgument(TemplateParm, TemplateParm->getType(), Default,
450 Converted)) {
Douglas Gregord684b002009-02-10 19:49:53 +0000451 TemplateParm->setInvalidDecl();
452 return;
453 }
454
Anders Carlssone9146f22009-05-01 19:49:17 +0000455 TemplateParm->setDefaultArgument(DefaultE.takeAs<Expr>());
Douglas Gregord684b002009-02-10 19:49:53 +0000456}
457
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000458
459/// ActOnTemplateTemplateParameter - Called when a C++ template template
460/// parameter (e.g. T in template <template <typename> class T> class array)
461/// has been parsed. S is the current scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000462Sema::DeclPtrTy Sema::ActOnTemplateTemplateParameter(Scope* S,
463 SourceLocation TmpLoc,
464 TemplateParamsTy *Params,
465 IdentifierInfo *Name,
466 SourceLocation NameLoc,
467 unsigned Depth,
Mike Stump1eb44332009-09-09 15:08:12 +0000468 unsigned Position) {
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000469 assert(S->isTemplateParamScope() &&
470 "Template template parameter not in template parameter scope!");
471
472 // Construct the parameter object.
473 TemplateTemplateParmDecl *Param =
474 TemplateTemplateParmDecl::Create(Context, CurContext, TmpLoc, Depth,
475 Position, Name,
476 (TemplateParameterList*)Params);
477
478 // Make sure the parameter is valid.
479 // FIXME: Decl object is not currently invalidated anywhere so this doesn't
480 // do anything yet. However, if the template parameter list or (eventual)
481 // default value is ever invalidated, that will propagate here.
482 bool Invalid = false;
483 if (Invalid) {
484 Param->setInvalidDecl();
485 }
486
487 // If the tt-param has a name, then link the identifier into the scope
488 // and lookup mechanisms.
489 if (Name) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000490 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000491 IdResolver.AddDecl(Param);
492 }
493
Chris Lattnerb28317a2009-03-28 19:18:32 +0000494 return DeclPtrTy::make(Param);
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000495}
496
Douglas Gregord684b002009-02-10 19:49:53 +0000497/// \brief Adds a default argument to the given template template
498/// parameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000499void Sema::ActOnTemplateTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregord684b002009-02-10 19:49:53 +0000500 SourceLocation EqualLoc,
501 ExprArg DefaultE) {
Mike Stump1eb44332009-09-09 15:08:12 +0000502 TemplateTemplateParmDecl *TemplateParm
Chris Lattnerb28317a2009-03-28 19:18:32 +0000503 = cast<TemplateTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregord684b002009-02-10 19:49:53 +0000504
505 // Since a template-template parameter's default argument is an
506 // id-expression, it must be a DeclRefExpr.
Mike Stump1eb44332009-09-09 15:08:12 +0000507 DeclRefExpr *Default
Douglas Gregord684b002009-02-10 19:49:53 +0000508 = cast<DeclRefExpr>(static_cast<Expr *>(DefaultE.get()));
509
510 // C++ [temp.param]p14:
511 // A template-parameter shall not be used in its own default argument.
512 // FIXME: Implement this check! Needs a recursive walk over the types.
513
514 // Check the well-formedness of the template argument.
515 if (!isa<TemplateDecl>(Default->getDecl())) {
Mike Stump1eb44332009-09-09 15:08:12 +0000516 Diag(Default->getSourceRange().getBegin(),
Douglas Gregord684b002009-02-10 19:49:53 +0000517 diag::err_template_arg_must_be_template)
518 << Default->getSourceRange();
519 TemplateParm->setInvalidDecl();
520 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000521 }
Douglas Gregord684b002009-02-10 19:49:53 +0000522 if (CheckTemplateArgument(TemplateParm, Default)) {
523 TemplateParm->setInvalidDecl();
524 return;
525 }
526
527 DefaultE.release();
528 TemplateParm->setDefaultArgument(Default);
529}
530
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000531/// ActOnTemplateParameterList - Builds a TemplateParameterList that
532/// contains the template parameters in Params/NumParams.
533Sema::TemplateParamsTy *
534Sema::ActOnTemplateParameterList(unsigned Depth,
535 SourceLocation ExportLoc,
Mike Stump1eb44332009-09-09 15:08:12 +0000536 SourceLocation TemplateLoc,
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000537 SourceLocation LAngleLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +0000538 DeclPtrTy *Params, unsigned NumParams,
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000539 SourceLocation RAngleLoc) {
540 if (ExportLoc.isValid())
541 Diag(ExportLoc, diag::note_template_export_unsupported);
542
Douglas Gregorddc29e12009-02-06 22:42:48 +0000543 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
Douglas Gregorbf4ea562009-09-15 16:23:51 +0000544 (NamedDecl**)Params, NumParams,
545 RAngleLoc);
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000546}
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000547
Douglas Gregor212e81c2009-03-25 00:13:59 +0000548Sema::DeclResult
John McCall0f434ec2009-07-31 02:45:11 +0000549Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
Douglas Gregorddc29e12009-02-06 22:42:48 +0000550 SourceLocation KWLoc, const CXXScopeSpec &SS,
551 IdentifierInfo *Name, SourceLocation NameLoc,
552 AttributeList *Attr,
Douglas Gregor05396e22009-08-25 17:23:04 +0000553 TemplateParameterList *TemplateParams,
Anders Carlsson5aeccdb2009-03-26 00:52:18 +0000554 AccessSpecifier AS) {
Mike Stump1eb44332009-09-09 15:08:12 +0000555 assert(TemplateParams && TemplateParams->size() > 0 &&
Douglas Gregor05396e22009-08-25 17:23:04 +0000556 "No template parameters");
John McCall0f434ec2009-07-31 02:45:11 +0000557 assert(TUK != TUK_Reference && "Can only declare or define class templates");
Douglas Gregord684b002009-02-10 19:49:53 +0000558 bool Invalid = false;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000559
560 // Check that we can declare a template here.
Douglas Gregor05396e22009-08-25 17:23:04 +0000561 if (CheckTemplateDeclScope(S, TemplateParams))
Douglas Gregor212e81c2009-03-25 00:13:59 +0000562 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000563
John McCall05b23ea2009-09-14 21:59:20 +0000564 TagDecl::TagKind Kind = TagDecl::getTagKindForTypeSpec(TagSpec);
565 assert(Kind != TagDecl::TK_enum && "can't build template of enumerated type");
Douglas Gregorddc29e12009-02-06 22:42:48 +0000566
567 // There is no such thing as an unnamed class template.
568 if (!Name) {
569 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregor212e81c2009-03-25 00:13:59 +0000570 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000571 }
572
573 // Find any previous declaration with this name.
Douglas Gregor05396e22009-08-25 17:23:04 +0000574 DeclContext *SemanticContext;
575 LookupResult Previous;
576 if (SS.isNotEmpty() && !SS.isInvalid()) {
Douglas Gregorf0510d42009-10-12 23:11:44 +0000577 if (RequireCompleteDeclContext(SS))
578 return true;
579
Douglas Gregor05396e22009-08-25 17:23:04 +0000580 SemanticContext = computeDeclContext(SS, true);
581 if (!SemanticContext) {
582 // FIXME: Produce a reasonable diagnostic here
583 return true;
584 }
Mike Stump1eb44332009-09-09 15:08:12 +0000585
John McCallf36e02d2009-10-09 21:13:30 +0000586 LookupQualifiedName(Previous, SemanticContext, Name, LookupOrdinaryName,
Douglas Gregor05396e22009-08-25 17:23:04 +0000587 true);
588 } else {
589 SemanticContext = CurContext;
John McCallf36e02d2009-10-09 21:13:30 +0000590 LookupName(Previous, S, Name, LookupOrdinaryName, true);
Douglas Gregor05396e22009-08-25 17:23:04 +0000591 }
Mike Stump1eb44332009-09-09 15:08:12 +0000592
Douglas Gregorddc29e12009-02-06 22:42:48 +0000593 assert(!Previous.isAmbiguous() && "Ambiguity in class template redecl?");
594 NamedDecl *PrevDecl = 0;
595 if (Previous.begin() != Previous.end())
596 PrevDecl = *Previous.begin();
597
Douglas Gregor6102d982009-09-26 07:05:09 +0000598 if (PrevDecl && TUK == TUK_Friend) {
599 // C++ [namespace.memdef]p3:
600 // [...] When looking for a prior declaration of a class or a function
601 // declared as a friend, and when the name of the friend class or
602 // function is neither a qualified name nor a template-id, scopes outside
603 // the innermost enclosing namespace scope are not considered.
604 DeclContext *OutermostContext = CurContext;
605 while (!OutermostContext->isFileContext())
606 OutermostContext = OutermostContext->getLookupParent();
607
608 if (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
609 OutermostContext->Encloses(PrevDecl->getDeclContext())) {
610 SemanticContext = PrevDecl->getDeclContext();
611 } else {
612 // Declarations in outer scopes don't matter. However, the outermost
613 // context we computed is the semntic context for our new
614 // declaration.
615 PrevDecl = 0;
616 SemanticContext = OutermostContext;
617 }
618 } else if (PrevDecl && !isDeclInScope(PrevDecl, SemanticContext, S))
Douglas Gregorc19ee3e2009-06-17 23:37:01 +0000619 PrevDecl = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000620
Douglas Gregorddc29e12009-02-06 22:42:48 +0000621 // If there is a previous declaration with the same name, check
622 // whether this is a valid redeclaration.
Mike Stump1eb44332009-09-09 15:08:12 +0000623 ClassTemplateDecl *PrevClassTemplate
Douglas Gregorddc29e12009-02-06 22:42:48 +0000624 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
Douglas Gregord7e5bdb2009-10-09 21:11:42 +0000625
626 // We may have found the injected-class-name of a class template,
627 // class template partial specialization, or class template specialization.
628 // In these cases, grab the template that is being defined or specialized.
629 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
630 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
631 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
632 PrevClassTemplate
633 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
634 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
635 PrevClassTemplate
636 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
637 ->getSpecializedTemplate();
638 }
639 }
640
Douglas Gregorddc29e12009-02-06 22:42:48 +0000641 if (PrevClassTemplate) {
642 // Ensure that the template parameter lists are compatible.
643 if (!TemplateParameterListsAreEqual(TemplateParams,
644 PrevClassTemplate->getTemplateParameters(),
645 /*Complain=*/true))
Douglas Gregor212e81c2009-03-25 00:13:59 +0000646 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000647
648 // C++ [temp.class]p4:
649 // In a redeclaration, partial specialization, explicit
650 // specialization or explicit instantiation of a class template,
651 // the class-key shall agree in kind with the original class
652 // template declaration (7.1.5.3).
653 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Douglas Gregor501c5ce2009-05-14 16:41:31 +0000654 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind, KWLoc, *Name)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000655 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora3a83512009-04-01 23:51:29 +0000656 << Name
Mike Stump1eb44332009-09-09 15:08:12 +0000657 << CodeModificationHint::CreateReplacement(KWLoc,
Douglas Gregora3a83512009-04-01 23:51:29 +0000658 PrevRecordDecl->getKindName());
Douglas Gregorddc29e12009-02-06 22:42:48 +0000659 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregora3a83512009-04-01 23:51:29 +0000660 Kind = PrevRecordDecl->getTagKind();
Douglas Gregorddc29e12009-02-06 22:42:48 +0000661 }
662
Douglas Gregorddc29e12009-02-06 22:42:48 +0000663 // Check for redefinition of this class template.
John McCall0f434ec2009-07-31 02:45:11 +0000664 if (TUK == TUK_Definition) {
Douglas Gregorddc29e12009-02-06 22:42:48 +0000665 if (TagDecl *Def = PrevRecordDecl->getDefinition(Context)) {
666 Diag(NameLoc, diag::err_redefinition) << Name;
667 Diag(Def->getLocation(), diag::note_previous_definition);
668 // FIXME: Would it make sense to try to "forget" the previous
669 // definition, as part of error recovery?
Douglas Gregor212e81c2009-03-25 00:13:59 +0000670 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000671 }
672 }
673 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
674 // Maybe we will complain about the shadowed template parameter.
675 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
676 // Just pretend that we didn't see the previous declaration.
677 PrevDecl = 0;
678 } else if (PrevDecl) {
679 // C++ [temp]p5:
680 // A class template shall not have the same name as any other
681 // template, class, function, object, enumeration, enumerator,
682 // namespace, or type in the same scope (3.3), except as specified
683 // in (14.5.4).
684 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
685 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor212e81c2009-03-25 00:13:59 +0000686 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000687 }
688
Douglas Gregord684b002009-02-10 19:49:53 +0000689 // Check the template parameter list of this declaration, possibly
690 // merging in the template parameter list from the previous class
691 // template declaration.
692 if (CheckTemplateParameterList(TemplateParams,
693 PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0))
694 Invalid = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000695
Douglas Gregor7da97d02009-05-10 22:57:19 +0000696 // FIXME: If we had a scope specifier, we better have a previous template
Douglas Gregorddc29e12009-02-06 22:42:48 +0000697 // declaration!
698
Mike Stump1eb44332009-09-09 15:08:12 +0000699 CXXRecordDecl *NewClass =
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000700 CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name, KWLoc,
Mike Stump1eb44332009-09-09 15:08:12 +0000701 PrevClassTemplate?
Douglas Gregoraafc0cc2009-05-15 19:11:46 +0000702 PrevClassTemplate->getTemplatedDecl() : 0,
703 /*DelayTypeCreation=*/true);
Douglas Gregorddc29e12009-02-06 22:42:48 +0000704
705 ClassTemplateDecl *NewTemplate
706 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
707 DeclarationName(Name), TemplateParams,
Douglas Gregor5953d8b2009-03-19 17:26:29 +0000708 NewClass, PrevClassTemplate);
Douglas Gregorbefc20e2009-03-26 00:10:35 +0000709 NewClass->setDescribedClassTemplate(NewTemplate);
710
Douglas Gregoraafc0cc2009-05-15 19:11:46 +0000711 // Build the type for the class template declaration now.
Mike Stump1eb44332009-09-09 15:08:12 +0000712 QualType T =
713 Context.getTypeDeclType(NewClass,
714 PrevClassTemplate?
715 PrevClassTemplate->getTemplatedDecl() : 0);
Douglas Gregoraafc0cc2009-05-15 19:11:46 +0000716 assert(T->isDependentType() && "Class template type is not dependent?");
717 (void)T;
718
Douglas Gregorfd056bc2009-10-13 16:30:37 +0000719 // If we are providing an explicit specialization of a member that is a
720 // class template, make a note of that.
721 if (PrevClassTemplate &&
722 PrevClassTemplate->getInstantiatedFromMemberTemplate())
723 PrevClassTemplate->setMemberSpecialization();
724
Anders Carlsson4cbe82c2009-03-26 01:24:28 +0000725 // Set the access specifier.
Douglas Gregord85bea22009-09-26 06:47:28 +0000726 if (!Invalid && TUK != TUK_Friend)
John McCall05b23ea2009-09-14 21:59:20 +0000727 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
Mike Stump1eb44332009-09-09 15:08:12 +0000728
Douglas Gregorddc29e12009-02-06 22:42:48 +0000729 // Set the lexical context of these templates
730 NewClass->setLexicalDeclContext(CurContext);
731 NewTemplate->setLexicalDeclContext(CurContext);
732
John McCall0f434ec2009-07-31 02:45:11 +0000733 if (TUK == TUK_Definition)
Douglas Gregorddc29e12009-02-06 22:42:48 +0000734 NewClass->startDefinition();
735
736 if (Attr)
Douglas Gregor9cdda0c2009-06-17 21:51:59 +0000737 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregorddc29e12009-02-06 22:42:48 +0000738
John McCall05b23ea2009-09-14 21:59:20 +0000739 if (TUK != TUK_Friend)
740 PushOnScopeChains(NewTemplate, S);
741 else {
Douglas Gregord85bea22009-09-26 06:47:28 +0000742 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
John McCall05b23ea2009-09-14 21:59:20 +0000743 NewTemplate->setAccess(PrevClassTemplate->getAccess());
Douglas Gregord85bea22009-09-26 06:47:28 +0000744 NewClass->setAccess(PrevClassTemplate->getAccess());
745 }
John McCall05b23ea2009-09-14 21:59:20 +0000746
Douglas Gregord85bea22009-09-26 06:47:28 +0000747 NewTemplate->setObjectOfFriendDecl(/* PreviouslyDeclared = */
748 PrevClassTemplate != NULL);
749
John McCall05b23ea2009-09-14 21:59:20 +0000750 // Friend templates are visible in fairly strange ways.
751 if (!CurContext->isDependentContext()) {
752 DeclContext *DC = SemanticContext->getLookupContext();
753 DC->makeDeclVisibleInContext(NewTemplate, /* Recoverable = */ false);
754 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
755 PushOnScopeChains(NewTemplate, EnclosingScope,
756 /* AddToContext = */ false);
757 }
Douglas Gregord85bea22009-09-26 06:47:28 +0000758
759 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
760 NewClass->getLocation(),
761 NewTemplate,
762 /*FIXME:*/NewClass->getLocation());
763 Friend->setAccess(AS_public);
764 CurContext->addDecl(Friend);
John McCall05b23ea2009-09-14 21:59:20 +0000765 }
Douglas Gregorddc29e12009-02-06 22:42:48 +0000766
Douglas Gregord684b002009-02-10 19:49:53 +0000767 if (Invalid) {
768 NewTemplate->setInvalidDecl();
769 NewClass->setInvalidDecl();
770 }
Chris Lattnerb28317a2009-03-28 19:18:32 +0000771 return DeclPtrTy::make(NewTemplate);
Douglas Gregorddc29e12009-02-06 22:42:48 +0000772}
773
Douglas Gregord684b002009-02-10 19:49:53 +0000774/// \brief Checks the validity of a template parameter list, possibly
775/// considering the template parameter list from a previous
776/// declaration.
777///
778/// If an "old" template parameter list is provided, it must be
779/// equivalent (per TemplateParameterListsAreEqual) to the "new"
780/// template parameter list.
781///
782/// \param NewParams Template parameter list for a new template
783/// declaration. This template parameter list will be updated with any
784/// default arguments that are carried through from the previous
785/// template parameter list.
786///
787/// \param OldParams If provided, template parameter list from a
788/// previous declaration of the same template. Default template
789/// arguments will be merged from the old template parameter list to
790/// the new template parameter list.
791///
792/// \returns true if an error occurred, false otherwise.
793bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
794 TemplateParameterList *OldParams) {
795 bool Invalid = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000796
Douglas Gregord684b002009-02-10 19:49:53 +0000797 // C++ [temp.param]p10:
798 // The set of default template-arguments available for use with a
799 // template declaration or definition is obtained by merging the
800 // default arguments from the definition (if in scope) and all
801 // declarations in scope in the same way default function
802 // arguments are (8.3.6).
803 bool SawDefaultArgument = false;
804 SourceLocation PreviousDefaultArgLoc;
Douglas Gregorc15cb382009-02-09 23:23:08 +0000805
Anders Carlsson49d25572009-06-12 23:20:15 +0000806 bool SawParameterPack = false;
807 SourceLocation ParameterPackLoc;
808
Mike Stump1a35fde2009-02-11 23:03:27 +0000809 // Dummy initialization to avoid warnings.
Douglas Gregor1bc69132009-02-11 20:46:19 +0000810 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregord684b002009-02-10 19:49:53 +0000811 if (OldParams)
812 OldParam = OldParams->begin();
813
814 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
815 NewParamEnd = NewParams->end();
816 NewParam != NewParamEnd; ++NewParam) {
817 // Variables used to diagnose redundant default arguments
818 bool RedundantDefaultArg = false;
819 SourceLocation OldDefaultLoc;
820 SourceLocation NewDefaultLoc;
821
822 // Variables used to diagnose missing default arguments
823 bool MissingDefaultArg = false;
824
Anders Carlsson49d25572009-06-12 23:20:15 +0000825 // C++0x [temp.param]p11:
826 // If a template parameter of a class template is a template parameter pack,
827 // it must be the last template parameter.
828 if (SawParameterPack) {
Mike Stump1eb44332009-09-09 15:08:12 +0000829 Diag(ParameterPackLoc,
Anders Carlsson49d25572009-06-12 23:20:15 +0000830 diag::err_template_param_pack_must_be_last_template_parameter);
831 Invalid = true;
832 }
833
Douglas Gregord684b002009-02-10 19:49:53 +0000834 // Merge default arguments for template type parameters.
835 if (TemplateTypeParmDecl *NewTypeParm
836 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000837 TemplateTypeParmDecl *OldTypeParm
Douglas Gregord684b002009-02-10 19:49:53 +0000838 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000839
Anders Carlsson49d25572009-06-12 23:20:15 +0000840 if (NewTypeParm->isParameterPack()) {
841 assert(!NewTypeParm->hasDefaultArgument() &&
842 "Parameter packs can't have a default argument!");
843 SawParameterPack = true;
844 ParameterPackLoc = NewTypeParm->getLocation();
Mike Stump1eb44332009-09-09 15:08:12 +0000845 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
Douglas Gregord684b002009-02-10 19:49:53 +0000846 NewTypeParm->hasDefaultArgument()) {
847 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
848 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
849 SawDefaultArgument = true;
850 RedundantDefaultArg = true;
851 PreviousDefaultArgLoc = NewDefaultLoc;
852 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
853 // Merge the default argument from the old declaration to the
854 // new declaration.
855 SawDefaultArgument = true;
856 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgument(),
857 OldTypeParm->getDefaultArgumentLoc(),
858 true);
859 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
860 } else if (NewTypeParm->hasDefaultArgument()) {
861 SawDefaultArgument = true;
862 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
863 } else if (SawDefaultArgument)
864 MissingDefaultArg = true;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000865 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
Douglas Gregord684b002009-02-10 19:49:53 +0000866 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000867 // Merge default arguments for non-type template parameters
Douglas Gregord684b002009-02-10 19:49:53 +0000868 NonTypeTemplateParmDecl *OldNonTypeParm
869 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000870 if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
Douglas Gregord684b002009-02-10 19:49:53 +0000871 NewNonTypeParm->hasDefaultArgument()) {
872 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
873 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
874 SawDefaultArgument = true;
875 RedundantDefaultArg = true;
876 PreviousDefaultArgLoc = NewDefaultLoc;
877 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
878 // Merge the default argument from the old declaration to the
879 // new declaration.
880 SawDefaultArgument = true;
881 // FIXME: We need to create a new kind of "default argument"
882 // expression that points to a previous template template
883 // parameter.
884 NewNonTypeParm->setDefaultArgument(
885 OldNonTypeParm->getDefaultArgument());
886 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
887 } else if (NewNonTypeParm->hasDefaultArgument()) {
888 SawDefaultArgument = true;
889 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
890 } else if (SawDefaultArgument)
Mike Stump1eb44332009-09-09 15:08:12 +0000891 MissingDefaultArg = true;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000892 } else {
Douglas Gregord684b002009-02-10 19:49:53 +0000893 // Merge default arguments for template template parameters
Douglas Gregord684b002009-02-10 19:49:53 +0000894 TemplateTemplateParmDecl *NewTemplateParm
895 = cast<TemplateTemplateParmDecl>(*NewParam);
896 TemplateTemplateParmDecl *OldTemplateParm
897 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000898 if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
Douglas Gregord684b002009-02-10 19:49:53 +0000899 NewTemplateParm->hasDefaultArgument()) {
900 OldDefaultLoc = OldTemplateParm->getDefaultArgumentLoc();
901 NewDefaultLoc = NewTemplateParm->getDefaultArgumentLoc();
902 SawDefaultArgument = true;
903 RedundantDefaultArg = true;
904 PreviousDefaultArgLoc = NewDefaultLoc;
905 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
906 // Merge the default argument from the old declaration to the
907 // new declaration.
908 SawDefaultArgument = true;
Mike Stump390b4cc2009-05-16 07:39:55 +0000909 // FIXME: We need to create a new kind of "default argument" expression
910 // that points to a previous template template parameter.
Douglas Gregord684b002009-02-10 19:49:53 +0000911 NewTemplateParm->setDefaultArgument(
912 OldTemplateParm->getDefaultArgument());
913 PreviousDefaultArgLoc = OldTemplateParm->getDefaultArgumentLoc();
914 } else if (NewTemplateParm->hasDefaultArgument()) {
915 SawDefaultArgument = true;
916 PreviousDefaultArgLoc = NewTemplateParm->getDefaultArgumentLoc();
917 } else if (SawDefaultArgument)
Mike Stump1eb44332009-09-09 15:08:12 +0000918 MissingDefaultArg = true;
Douglas Gregord684b002009-02-10 19:49:53 +0000919 }
920
921 if (RedundantDefaultArg) {
922 // C++ [temp.param]p12:
923 // A template-parameter shall not be given default arguments
924 // by two different declarations in the same scope.
925 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
926 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
927 Invalid = true;
928 } else if (MissingDefaultArg) {
929 // C++ [temp.param]p11:
930 // If a template-parameter has a default template-argument,
931 // all subsequent template-parameters shall have a default
932 // template-argument supplied.
Mike Stump1eb44332009-09-09 15:08:12 +0000933 Diag((*NewParam)->getLocation(),
Douglas Gregord684b002009-02-10 19:49:53 +0000934 diag::err_template_param_default_arg_missing);
935 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
936 Invalid = true;
937 }
938
939 // If we have an old template parameter list that we're merging
940 // in, move on to the next parameter.
941 if (OldParams)
942 ++OldParam;
943 }
944
945 return Invalid;
946}
Douglas Gregorc15cb382009-02-09 23:23:08 +0000947
Mike Stump1eb44332009-09-09 15:08:12 +0000948/// \brief Match the given template parameter lists to the given scope
Douglas Gregorf59a56e2009-07-21 23:53:31 +0000949/// specifier, returning the template parameter list that applies to the
950/// name.
951///
952/// \param DeclStartLoc the start of the declaration that has a scope
953/// specifier or a template parameter list.
Mike Stump1eb44332009-09-09 15:08:12 +0000954///
Douglas Gregorf59a56e2009-07-21 23:53:31 +0000955/// \param SS the scope specifier that will be matched to the given template
956/// parameter lists. This scope specifier precedes a qualified name that is
957/// being declared.
958///
959/// \param ParamLists the template parameter lists, from the outermost to the
960/// innermost template parameter lists.
961///
962/// \param NumParamLists the number of template parameter lists in ParamLists.
963///
Douglas Gregor1fef4e62009-10-07 22:35:40 +0000964/// \param IsExplicitSpecialization will be set true if the entity being
965/// declared is an explicit specialization, false otherwise.
966///
Mike Stump1eb44332009-09-09 15:08:12 +0000967/// \returns the template parameter list, if any, that corresponds to the
Douglas Gregorf59a56e2009-07-21 23:53:31 +0000968/// name that is preceded by the scope specifier @p SS. This template
969/// parameter list may be have template parameters (if we're declaring a
Mike Stump1eb44332009-09-09 15:08:12 +0000970/// template) or may have no template parameters (if we're declaring a
Douglas Gregorf59a56e2009-07-21 23:53:31 +0000971/// template specialization), or may be NULL (if we were's declaring isn't
972/// itself a template).
973TemplateParameterList *
974Sema::MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc,
975 const CXXScopeSpec &SS,
976 TemplateParameterList **ParamLists,
Douglas Gregor1fef4e62009-10-07 22:35:40 +0000977 unsigned NumParamLists,
978 bool &IsExplicitSpecialization) {
979 IsExplicitSpecialization = false;
980
Douglas Gregorf59a56e2009-07-21 23:53:31 +0000981 // Find the template-ids that occur within the nested-name-specifier. These
982 // template-ids will match up with the template parameter lists.
983 llvm::SmallVector<const TemplateSpecializationType *, 4>
984 TemplateIdsInSpecifier;
985 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
986 NNS; NNS = NNS->getPrefix()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000987 if (const TemplateSpecializationType *SpecType
Douglas Gregorf59a56e2009-07-21 23:53:31 +0000988 = dyn_cast_or_null<TemplateSpecializationType>(NNS->getAsType())) {
989 TemplateDecl *Template = SpecType->getTemplateName().getAsTemplateDecl();
990 if (!Template)
991 continue; // FIXME: should this be an error? probably...
Mike Stump1eb44332009-09-09 15:08:12 +0000992
Ted Kremenek6217b802009-07-29 21:53:49 +0000993 if (const RecordType *Record = SpecType->getAs<RecordType>()) {
Douglas Gregorf59a56e2009-07-21 23:53:31 +0000994 ClassTemplateSpecializationDecl *SpecDecl
995 = cast<ClassTemplateSpecializationDecl>(Record->getDecl());
996 // If the nested name specifier refers to an explicit specialization,
997 // we don't need a template<> header.
Douglas Gregor861d0e82009-09-16 00:01:48 +0000998 // FIXME: revisit this approach once we cope with specializations
Douglas Gregorb88e8882009-07-30 17:40:51 +0000999 // properly.
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001000 if (SpecDecl->getSpecializationKind() == TSK_ExplicitSpecialization)
1001 continue;
1002 }
Mike Stump1eb44332009-09-09 15:08:12 +00001003
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001004 TemplateIdsInSpecifier.push_back(SpecType);
1005 }
1006 }
Mike Stump1eb44332009-09-09 15:08:12 +00001007
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001008 // Reverse the list of template-ids in the scope specifier, so that we can
1009 // more easily match up the template-ids and the template parameter lists.
1010 std::reverse(TemplateIdsInSpecifier.begin(), TemplateIdsInSpecifier.end());
Mike Stump1eb44332009-09-09 15:08:12 +00001011
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001012 SourceLocation FirstTemplateLoc = DeclStartLoc;
1013 if (NumParamLists)
1014 FirstTemplateLoc = ParamLists[0]->getTemplateLoc();
Mike Stump1eb44332009-09-09 15:08:12 +00001015
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001016 // Match the template-ids found in the specifier to the template parameter
1017 // lists.
1018 unsigned Idx = 0;
1019 for (unsigned NumTemplateIds = TemplateIdsInSpecifier.size();
1020 Idx != NumTemplateIds; ++Idx) {
Douglas Gregorb88e8882009-07-30 17:40:51 +00001021 QualType TemplateId = QualType(TemplateIdsInSpecifier[Idx], 0);
1022 bool DependentTemplateId = TemplateId->isDependentType();
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001023 if (Idx >= NumParamLists) {
1024 // We have a template-id without a corresponding template parameter
1025 // list.
1026 if (DependentTemplateId) {
Mike Stump1eb44332009-09-09 15:08:12 +00001027 // FIXME: the location information here isn't great.
1028 Diag(SS.getRange().getBegin(),
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001029 diag::err_template_spec_needs_template_parameters)
Douglas Gregorb88e8882009-07-30 17:40:51 +00001030 << TemplateId
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001031 << SS.getRange();
1032 } else {
1033 Diag(SS.getRange().getBegin(), diag::err_template_spec_needs_header)
1034 << SS.getRange()
1035 << CodeModificationHint::CreateInsertion(FirstTemplateLoc,
1036 "template<> ");
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001037 IsExplicitSpecialization = true;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001038 }
1039 return 0;
1040 }
Mike Stump1eb44332009-09-09 15:08:12 +00001041
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001042 // Check the template parameter list against its corresponding template-id.
Douglas Gregorb88e8882009-07-30 17:40:51 +00001043 if (DependentTemplateId) {
Mike Stump1eb44332009-09-09 15:08:12 +00001044 TemplateDecl *Template
Douglas Gregorb88e8882009-07-30 17:40:51 +00001045 = TemplateIdsInSpecifier[Idx]->getTemplateName().getAsTemplateDecl();
1046
Mike Stump1eb44332009-09-09 15:08:12 +00001047 if (ClassTemplateDecl *ClassTemplate
Douglas Gregorb88e8882009-07-30 17:40:51 +00001048 = dyn_cast<ClassTemplateDecl>(Template)) {
1049 TemplateParameterList *ExpectedTemplateParams = 0;
1050 // Is this template-id naming the primary template?
1051 if (Context.hasSameType(TemplateId,
1052 ClassTemplate->getInjectedClassNameType(Context)))
1053 ExpectedTemplateParams = ClassTemplate->getTemplateParameters();
1054 // ... or a partial specialization?
1055 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
1056 = ClassTemplate->findPartialSpecialization(TemplateId))
1057 ExpectedTemplateParams = PartialSpec->getTemplateParameters();
1058
1059 if (ExpectedTemplateParams)
Mike Stump1eb44332009-09-09 15:08:12 +00001060 TemplateParameterListsAreEqual(ParamLists[Idx],
Douglas Gregorb88e8882009-07-30 17:40:51 +00001061 ExpectedTemplateParams,
1062 true);
Mike Stump1eb44332009-09-09 15:08:12 +00001063 }
Douglas Gregorb88e8882009-07-30 17:40:51 +00001064 } else if (ParamLists[Idx]->size() > 0)
Mike Stump1eb44332009-09-09 15:08:12 +00001065 Diag(ParamLists[Idx]->getTemplateLoc(),
Douglas Gregorb88e8882009-07-30 17:40:51 +00001066 diag::err_template_param_list_matches_nontemplate)
1067 << TemplateId
1068 << ParamLists[Idx]->getSourceRange();
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001069 else
1070 IsExplicitSpecialization = true;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001071 }
Mike Stump1eb44332009-09-09 15:08:12 +00001072
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001073 // If there were at least as many template-ids as there were template
1074 // parameter lists, then there are no template parameter lists remaining for
1075 // the declaration itself.
1076 if (Idx >= NumParamLists)
1077 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001078
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001079 // If there were too many template parameter lists, complain about that now.
1080 if (Idx != NumParamLists - 1) {
1081 while (Idx < NumParamLists - 1) {
Mike Stump1eb44332009-09-09 15:08:12 +00001082 Diag(ParamLists[Idx]->getTemplateLoc(),
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001083 diag::err_template_spec_extra_headers)
1084 << SourceRange(ParamLists[Idx]->getTemplateLoc(),
1085 ParamLists[Idx]->getRAngleLoc());
1086 ++Idx;
1087 }
1088 }
Mike Stump1eb44332009-09-09 15:08:12 +00001089
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001090 // Return the last template parameter list, which corresponds to the
1091 // entity being declared.
1092 return ParamLists[NumParamLists - 1];
1093}
1094
Douglas Gregor40808ce2009-03-09 23:48:35 +00001095/// \brief Translates template arguments as provided by the parser
1096/// into template arguments used by semantic analysis.
Douglas Gregor0b60d9e2009-09-25 23:53:26 +00001097void Sema::translateTemplateArguments(ASTTemplateArgsPtr &TemplateArgsIn,
1098 SourceLocation *TemplateArgLocs,
Douglas Gregor40808ce2009-03-09 23:48:35 +00001099 llvm::SmallVector<TemplateArgument, 16> &TemplateArgs) {
1100 TemplateArgs.reserve(TemplateArgsIn.size());
1101
1102 void **Args = TemplateArgsIn.getArgs();
1103 bool *ArgIsType = TemplateArgsIn.getArgIsType();
1104 for (unsigned Arg = 0, Last = TemplateArgsIn.size(); Arg != Last; ++Arg) {
1105 TemplateArgs.push_back(
1106 ArgIsType[Arg]? TemplateArgument(TemplateArgLocs[Arg],
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00001107 //FIXME: Preserve type source info.
1108 Sema::GetTypeFromParser(Args[Arg]))
Douglas Gregor40808ce2009-03-09 23:48:35 +00001109 : TemplateArgument(reinterpret_cast<Expr *>(Args[Arg])));
1110 }
1111}
1112
Douglas Gregor7532dc62009-03-30 22:58:21 +00001113QualType Sema::CheckTemplateIdType(TemplateName Name,
1114 SourceLocation TemplateLoc,
1115 SourceLocation LAngleLoc,
1116 const TemplateArgument *TemplateArgs,
1117 unsigned NumTemplateArgs,
1118 SourceLocation RAngleLoc) {
1119 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregorc45c2322009-03-31 00:43:58 +00001120 if (!Template) {
1121 // The template name does not resolve to a template, so we just
1122 // build a dependent template-id type.
Douglas Gregorc45c2322009-03-31 00:43:58 +00001123 return Context.getTemplateSpecializationType(Name, TemplateArgs,
Douglas Gregor1275ae02009-07-28 23:00:59 +00001124 NumTemplateArgs);
Douglas Gregorc45c2322009-03-31 00:43:58 +00001125 }
Douglas Gregor7532dc62009-03-30 22:58:21 +00001126
Douglas Gregor40808ce2009-03-09 23:48:35 +00001127 // Check that the template argument list is well-formed for this
1128 // template.
Anders Carlssonfb250522009-06-23 01:26:57 +00001129 TemplateArgumentListBuilder Converted(Template->getTemplateParameters(),
1130 NumTemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00001131 if (CheckTemplateArgumentList(Template, TemplateLoc, LAngleLoc,
Douglas Gregor40808ce2009-03-09 23:48:35 +00001132 TemplateArgs, NumTemplateArgs, RAngleLoc,
Douglas Gregor16134c62009-07-01 00:28:38 +00001133 false, Converted))
Douglas Gregor40808ce2009-03-09 23:48:35 +00001134 return QualType();
1135
Mike Stump1eb44332009-09-09 15:08:12 +00001136 assert((Converted.structuredSize() ==
Douglas Gregor7532dc62009-03-30 22:58:21 +00001137 Template->getTemplateParameters()->size()) &&
Douglas Gregor40808ce2009-03-09 23:48:35 +00001138 "Converted template argument list is too short!");
1139
1140 QualType CanonType;
1141
Douglas Gregor7532dc62009-03-30 22:58:21 +00001142 if (TemplateSpecializationType::anyDependentTemplateArguments(
Douglas Gregor40808ce2009-03-09 23:48:35 +00001143 TemplateArgs,
1144 NumTemplateArgs)) {
1145 // This class template specialization is a dependent
1146 // type. Therefore, its canonical type is another class template
1147 // specialization type that contains all of the converted
1148 // arguments in canonical form. This ensures that, e.g., A<T> and
1149 // A<T, T> have identical types when A is declared as:
1150 //
1151 // template<typename T, typename U = T> struct A;
Douglas Gregor25a3ef72009-05-07 06:41:52 +00001152 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
Mike Stump1eb44332009-09-09 15:08:12 +00001153 CanonType = Context.getTemplateSpecializationType(CanonName,
Anders Carlssonfb250522009-06-23 01:26:57 +00001154 Converted.getFlatArguments(),
1155 Converted.flatSize());
Mike Stump1eb44332009-09-09 15:08:12 +00001156
Douglas Gregor1275ae02009-07-28 23:00:59 +00001157 // FIXME: CanonType is not actually the canonical type, and unfortunately
1158 // it is a TemplateTypeSpecializationType that we will never use again.
1159 // In the future, we need to teach getTemplateSpecializationType to only
1160 // build the canonical type and return that to us.
1161 CanonType = Context.getCanonicalType(CanonType);
Mike Stump1eb44332009-09-09 15:08:12 +00001162 } else if (ClassTemplateDecl *ClassTemplate
Douglas Gregor7532dc62009-03-30 22:58:21 +00001163 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00001164 // Find the class template specialization declaration that
1165 // corresponds to these arguments.
1166 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001167 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlssonfb250522009-06-23 01:26:57 +00001168 Converted.getFlatArguments(),
Douglas Gregor828e2262009-07-29 16:09:57 +00001169 Converted.flatSize(),
1170 Context);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001171 void *InsertPos = 0;
1172 ClassTemplateSpecializationDecl *Decl
1173 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
1174 if (!Decl) {
1175 // This is the first time we have referenced this class template
1176 // specialization. Create the canonical declaration and add it to
1177 // the set of specializations.
Mike Stump1eb44332009-09-09 15:08:12 +00001178 Decl = ClassTemplateSpecializationDecl::Create(Context,
Anders Carlsson1c5976e2009-06-05 03:43:12 +00001179 ClassTemplate->getDeclContext(),
John McCall9cc78072009-09-11 07:25:08 +00001180 ClassTemplate->getLocation(),
Anders Carlsson1c5976e2009-06-05 03:43:12 +00001181 ClassTemplate,
Anders Carlssonfb250522009-06-23 01:26:57 +00001182 Converted, 0);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001183 ClassTemplate->getSpecializations().InsertNode(Decl, InsertPos);
1184 Decl->setLexicalDeclContext(CurContext);
1185 }
1186
1187 CanonType = Context.getTypeDeclType(Decl);
1188 }
Mike Stump1eb44332009-09-09 15:08:12 +00001189
Douglas Gregor40808ce2009-03-09 23:48:35 +00001190 // Build the fully-sugared type for this class template
1191 // specialization, which refers back to the class template
1192 // specialization we created or found.
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00001193 //FIXME: Preserve type source info.
Douglas Gregor7532dc62009-03-30 22:58:21 +00001194 return Context.getTemplateSpecializationType(Name, TemplateArgs,
1195 NumTemplateArgs, CanonType);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001196}
1197
Douglas Gregorcc636682009-02-17 23:15:12 +00001198Action::TypeResult
Douglas Gregor7532dc62009-03-30 22:58:21 +00001199Sema::ActOnTemplateIdType(TemplateTy TemplateD, SourceLocation TemplateLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00001200 SourceLocation LAngleLoc,
Douglas Gregor7532dc62009-03-30 22:58:21 +00001201 ASTTemplateArgsPtr TemplateArgsIn,
1202 SourceLocation *TemplateArgLocs,
John McCall6b2becf2009-09-08 17:47:29 +00001203 SourceLocation RAngleLoc) {
Douglas Gregor7532dc62009-03-30 22:58:21 +00001204 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Douglas Gregor55f6b142009-02-09 18:46:07 +00001205
Douglas Gregor40808ce2009-03-09 23:48:35 +00001206 // Translate the parser's template argument list in our AST format.
1207 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
1208 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
Douglas Gregorc15cb382009-02-09 23:23:08 +00001209
Douglas Gregor7532dc62009-03-30 22:58:21 +00001210 QualType Result = CheckTemplateIdType(Template, TemplateLoc, LAngleLoc,
Jay Foadbeaaccd2009-05-21 09:52:38 +00001211 TemplateArgs.data(),
1212 TemplateArgs.size(),
Douglas Gregor7532dc62009-03-30 22:58:21 +00001213 RAngleLoc);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001214 TemplateArgsIn.release();
Douglas Gregor31a19b62009-04-01 21:51:26 +00001215
1216 if (Result.isNull())
1217 return true;
1218
John McCall6b2becf2009-09-08 17:47:29 +00001219 return Result.getAsOpaquePtr();
1220}
John McCallf1bbbb42009-09-04 01:14:41 +00001221
John McCall6b2becf2009-09-08 17:47:29 +00001222Sema::TypeResult Sema::ActOnTagTemplateIdType(TypeResult TypeResult,
1223 TagUseKind TUK,
1224 DeclSpec::TST TagSpec,
1225 SourceLocation TagLoc) {
1226 if (TypeResult.isInvalid())
1227 return Sema::TypeResult();
John McCallf1bbbb42009-09-04 01:14:41 +00001228
John McCall6b2becf2009-09-08 17:47:29 +00001229 QualType Type = QualType::getFromOpaquePtr(TypeResult.get());
John McCallf1bbbb42009-09-04 01:14:41 +00001230
John McCall6b2becf2009-09-08 17:47:29 +00001231 // Verify the tag specifier.
1232 TagDecl::TagKind TagKind = TagDecl::getTagKindForTypeSpec(TagSpec);
Mike Stump1eb44332009-09-09 15:08:12 +00001233
John McCall6b2becf2009-09-08 17:47:29 +00001234 if (const RecordType *RT = Type->getAs<RecordType>()) {
1235 RecordDecl *D = RT->getDecl();
1236
1237 IdentifierInfo *Id = D->getIdentifier();
1238 assert(Id && "templated class must have an identifier");
1239
1240 if (!isAcceptableTagRedeclaration(D, TagKind, TagLoc, *Id)) {
1241 Diag(TagLoc, diag::err_use_with_wrong_tag)
John McCallc4e70192009-09-11 04:59:25 +00001242 << Type
John McCall6b2becf2009-09-08 17:47:29 +00001243 << CodeModificationHint::CreateReplacement(SourceRange(TagLoc),
1244 D->getKindName());
John McCallc4e70192009-09-11 04:59:25 +00001245 Diag(D->getLocation(), diag::note_previous_use);
John McCallf1bbbb42009-09-04 01:14:41 +00001246 }
1247 }
1248
John McCall6b2becf2009-09-08 17:47:29 +00001249 QualType ElabType = Context.getElaboratedType(Type, TagKind);
1250
1251 return ElabType.getAsOpaquePtr();
Douglas Gregor55f6b142009-02-09 18:46:07 +00001252}
1253
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001254Sema::OwningExprResult Sema::BuildTemplateIdExpr(TemplateName Template,
1255 SourceLocation TemplateNameLoc,
1256 SourceLocation LAngleLoc,
1257 const TemplateArgument *TemplateArgs,
1258 unsigned NumTemplateArgs,
1259 SourceLocation RAngleLoc) {
1260 // FIXME: Can we do any checking at this point? I guess we could check the
1261 // template arguments that we have against the template name, if the template
Mike Stump1eb44332009-09-09 15:08:12 +00001262 // name refers to a single template. That's not a terribly common case,
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001263 // though.
Mike Stump1eb44332009-09-09 15:08:12 +00001264 return Owned(TemplateIdRefExpr::Create(Context,
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001265 /*FIXME: New type?*/Context.OverloadTy,
1266 /*FIXME: Necessary?*/0,
1267 /*FIXME: Necessary?*/SourceRange(),
1268 Template, TemplateNameLoc, LAngleLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00001269 TemplateArgs,
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001270 NumTemplateArgs, RAngleLoc));
1271}
1272
1273Sema::OwningExprResult Sema::ActOnTemplateIdExpr(TemplateTy TemplateD,
1274 SourceLocation TemplateNameLoc,
1275 SourceLocation LAngleLoc,
1276 ASTTemplateArgsPtr TemplateArgsIn,
1277 SourceLocation *TemplateArgLocs,
1278 SourceLocation RAngleLoc) {
1279 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Mike Stump1eb44332009-09-09 15:08:12 +00001280
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001281 // Translate the parser's template argument list in our AST format.
1282 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
1283 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001284 TemplateArgsIn.release();
Mike Stump1eb44332009-09-09 15:08:12 +00001285
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001286 return BuildTemplateIdExpr(Template, TemplateNameLoc, LAngleLoc,
1287 TemplateArgs.data(), TemplateArgs.size(),
1288 RAngleLoc);
1289}
1290
Douglas Gregorc4bf26f2009-09-01 00:37:14 +00001291Sema::OwningExprResult
1292Sema::ActOnMemberTemplateIdReferenceExpr(Scope *S, ExprArg Base,
1293 SourceLocation OpLoc,
1294 tok::TokenKind OpKind,
1295 const CXXScopeSpec &SS,
1296 TemplateTy TemplateD,
1297 SourceLocation TemplateNameLoc,
1298 SourceLocation LAngleLoc,
1299 ASTTemplateArgsPtr TemplateArgsIn,
1300 SourceLocation *TemplateArgLocs,
1301 SourceLocation RAngleLoc) {
1302 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Mike Stump1eb44332009-09-09 15:08:12 +00001303
Douglas Gregorc4bf26f2009-09-01 00:37:14 +00001304 // FIXME: We're going to end up looking up the template based on its name,
1305 // twice!
1306 DeclarationName Name;
1307 if (TemplateDecl *ActualTemplate = Template.getAsTemplateDecl())
1308 Name = ActualTemplate->getDeclName();
1309 else if (OverloadedFunctionDecl *Ovl = Template.getAsOverloadedFunctionDecl())
1310 Name = Ovl->getDeclName();
1311 else
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00001312 Name = Template.getAsDependentTemplateName()->getName();
Mike Stump1eb44332009-09-09 15:08:12 +00001313
Douglas Gregorc4bf26f2009-09-01 00:37:14 +00001314 // Translate the parser's template argument list in our AST format.
1315 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
1316 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
1317 TemplateArgsIn.release();
Mike Stump1eb44332009-09-09 15:08:12 +00001318
Douglas Gregorc4bf26f2009-09-01 00:37:14 +00001319 // Do we have the save the actual template name? We might need it...
1320 return BuildMemberReferenceExpr(S, move(Base), OpLoc, OpKind, TemplateNameLoc,
1321 Name, true, LAngleLoc,
1322 TemplateArgs.data(), TemplateArgs.size(),
Mike Stump1eb44332009-09-09 15:08:12 +00001323 RAngleLoc, DeclPtrTy(), &SS);
Douglas Gregorc4bf26f2009-09-01 00:37:14 +00001324}
1325
Douglas Gregorc45c2322009-03-31 00:43:58 +00001326/// \brief Form a dependent template name.
1327///
1328/// This action forms a dependent template name given the template
1329/// name and its (presumably dependent) scope specifier. For
1330/// example, given "MetaFun::template apply", the scope specifier \p
1331/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
1332/// of the "template" keyword, and "apply" is the \p Name.
Mike Stump1eb44332009-09-09 15:08:12 +00001333Sema::TemplateTy
Douglas Gregorc45c2322009-03-31 00:43:58 +00001334Sema::ActOnDependentTemplateName(SourceLocation TemplateKWLoc,
1335 const IdentifierInfo &Name,
1336 SourceLocation NameLoc,
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001337 const CXXScopeSpec &SS,
1338 TypeTy *ObjectType) {
Mike Stump1eb44332009-09-09 15:08:12 +00001339 if ((ObjectType &&
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001340 computeDeclContext(QualType::getFromOpaquePtr(ObjectType))) ||
1341 (SS.isSet() && computeDeclContext(SS, false))) {
Douglas Gregorc45c2322009-03-31 00:43:58 +00001342 // C++0x [temp.names]p5:
1343 // If a name prefixed by the keyword template is not the name of
1344 // a template, the program is ill-formed. [Note: the keyword
1345 // template may not be applied to non-template members of class
1346 // templates. -end note ] [ Note: as is the case with the
1347 // typename prefix, the template prefix is allowed in cases
1348 // where it is not strictly necessary; i.e., when the
1349 // nested-name-specifier or the expression on the left of the ->
1350 // or . is not dependent on a template-parameter, or the use
1351 // does not appear in the scope of a template. -end note]
1352 //
1353 // Note: C++03 was more strict here, because it banned the use of
1354 // the "template" keyword prior to a template-name that was not a
1355 // dependent name. C++ DR468 relaxed this requirement (the
1356 // "template" keyword is now permitted). We follow the C++0x
1357 // rules, even in C++03 mode, retroactively applying the DR.
1358 TemplateTy Template;
Mike Stump1eb44332009-09-09 15:08:12 +00001359 TemplateNameKind TNK = isTemplateName(0, Name, NameLoc, &SS, ObjectType,
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001360 false, Template);
Douglas Gregorc45c2322009-03-31 00:43:58 +00001361 if (TNK == TNK_Non_template) {
1362 Diag(NameLoc, diag::err_template_kw_refers_to_non_template)
1363 << &Name;
1364 return TemplateTy();
1365 }
1366
1367 return Template;
1368 }
1369
Mike Stump1eb44332009-09-09 15:08:12 +00001370 NestedNameSpecifier *Qualifier
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001371 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Douglas Gregorc45c2322009-03-31 00:43:58 +00001372 return TemplateTy::make(Context.getDependentTemplateName(Qualifier, &Name));
1373}
1374
Mike Stump1eb44332009-09-09 15:08:12 +00001375bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
Anders Carlsson436b1562009-06-13 00:33:33 +00001376 const TemplateArgument &Arg,
1377 TemplateArgumentListBuilder &Converted) {
1378 // Check template type parameter.
1379 if (Arg.getKind() != TemplateArgument::Type) {
1380 // C++ [temp.arg.type]p1:
1381 // A template-argument for a template-parameter which is a
1382 // type shall be a type-id.
1383
1384 // We have a template type parameter but the template argument
1385 // is not a type.
1386 Diag(Arg.getLocation(), diag::err_template_arg_must_be_type);
1387 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump1eb44332009-09-09 15:08:12 +00001388
Anders Carlsson436b1562009-06-13 00:33:33 +00001389 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001390 }
Anders Carlsson436b1562009-06-13 00:33:33 +00001391
1392 if (CheckTemplateArgument(Param, Arg.getAsType(), Arg.getLocation()))
1393 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001394
Anders Carlsson436b1562009-06-13 00:33:33 +00001395 // Add the converted template type argument.
Anders Carlssonfb250522009-06-23 01:26:57 +00001396 Converted.Append(
Anders Carlsson436b1562009-06-13 00:33:33 +00001397 TemplateArgument(Arg.getLocation(),
1398 Context.getCanonicalType(Arg.getAsType())));
1399 return false;
1400}
1401
Douglas Gregorc15cb382009-02-09 23:23:08 +00001402/// \brief Check that the given template argument list is well-formed
1403/// for specializing the given template.
1404bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
1405 SourceLocation TemplateLoc,
1406 SourceLocation LAngleLoc,
Douglas Gregor40808ce2009-03-09 23:48:35 +00001407 const TemplateArgument *TemplateArgs,
1408 unsigned NumTemplateArgs,
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001409 SourceLocation RAngleLoc,
Douglas Gregor16134c62009-07-01 00:28:38 +00001410 bool PartialTemplateArgs,
Anders Carlsson1c5976e2009-06-05 03:43:12 +00001411 TemplateArgumentListBuilder &Converted) {
Douglas Gregorc15cb382009-02-09 23:23:08 +00001412 TemplateParameterList *Params = Template->getTemplateParameters();
1413 unsigned NumParams = Params->size();
Douglas Gregor40808ce2009-03-09 23:48:35 +00001414 unsigned NumArgs = NumTemplateArgs;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001415 bool Invalid = false;
1416
Mike Stump1eb44332009-09-09 15:08:12 +00001417 bool HasParameterPack =
Anders Carlsson0ceffb52009-06-13 02:08:00 +00001418 NumParams > 0 && Params->getParam(NumParams - 1)->isTemplateParameterPack();
Mike Stump1eb44332009-09-09 15:08:12 +00001419
Anders Carlsson0ceffb52009-06-13 02:08:00 +00001420 if ((NumArgs > NumParams && !HasParameterPack) ||
Douglas Gregor16134c62009-07-01 00:28:38 +00001421 (NumArgs < Params->getMinRequiredArguments() &&
1422 !PartialTemplateArgs)) {
Douglas Gregorc15cb382009-02-09 23:23:08 +00001423 // FIXME: point at either the first arg beyond what we can handle,
1424 // or the '>', depending on whether we have too many or too few
1425 // arguments.
1426 SourceRange Range;
1427 if (NumArgs > NumParams)
Douglas Gregor40808ce2009-03-09 23:48:35 +00001428 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
Douglas Gregorc15cb382009-02-09 23:23:08 +00001429 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
1430 << (NumArgs > NumParams)
1431 << (isa<ClassTemplateDecl>(Template)? 0 :
1432 isa<FunctionTemplateDecl>(Template)? 1 :
1433 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
1434 << Template << Range;
Douglas Gregor62cb18d2009-02-11 18:16:40 +00001435 Diag(Template->getLocation(), diag::note_template_decl_here)
1436 << Params->getSourceRange();
Douglas Gregorc15cb382009-02-09 23:23:08 +00001437 Invalid = true;
1438 }
Mike Stump1eb44332009-09-09 15:08:12 +00001439
1440 // C++ [temp.arg]p1:
Douglas Gregorc15cb382009-02-09 23:23:08 +00001441 // [...] The type and form of each template-argument specified in
1442 // a template-id shall match the type and form specified for the
1443 // corresponding parameter declared by the template in its
1444 // template-parameter-list.
1445 unsigned ArgIdx = 0;
1446 for (TemplateParameterList::iterator Param = Params->begin(),
1447 ParamEnd = Params->end();
1448 Param != ParamEnd; ++Param, ++ArgIdx) {
Douglas Gregor16134c62009-07-01 00:28:38 +00001449 if (ArgIdx > NumArgs && PartialTemplateArgs)
1450 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001451
Douglas Gregorc15cb382009-02-09 23:23:08 +00001452 // Decode the template argument
Douglas Gregor40808ce2009-03-09 23:48:35 +00001453 TemplateArgument Arg;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001454 if (ArgIdx >= NumArgs) {
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001455 // Retrieve the default template argument from the template
1456 // parameter.
1457 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
Anders Carlsson0ceffb52009-06-13 02:08:00 +00001458 if (TTP->isParameterPack()) {
Anders Carlssonfb250522009-06-23 01:26:57 +00001459 // We have an empty argument pack.
1460 Converted.BeginPack();
1461 Converted.EndPack();
Anders Carlsson0ceffb52009-06-13 02:08:00 +00001462 break;
1463 }
Mike Stump1eb44332009-09-09 15:08:12 +00001464
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001465 if (!TTP->hasDefaultArgument())
1466 break;
1467
Douglas Gregor40808ce2009-03-09 23:48:35 +00001468 QualType ArgType = TTP->getDefaultArgument();
Douglas Gregor99ebf652009-02-27 19:31:52 +00001469
1470 // If the argument type is dependent, instantiate it now based
1471 // on the previously-computed template arguments.
Douglas Gregordf667e72009-03-10 20:44:00 +00001472 if (ArgType->isDependentType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001473 InstantiatingTemplate Inst(*this, TemplateLoc,
Anders Carlssonfb250522009-06-23 01:26:57 +00001474 Template, Converted.getFlatArguments(),
Anders Carlsson1c5976e2009-06-05 03:43:12 +00001475 Converted.flatSize(),
Douglas Gregordf667e72009-03-10 20:44:00 +00001476 SourceRange(TemplateLoc, RAngleLoc));
Douglas Gregor7e063902009-05-11 23:53:27 +00001477
Anders Carlssone9c904b2009-06-05 04:47:51 +00001478 TemplateArgumentList TemplateArgs(Context, Converted,
Anders Carlssonfb250522009-06-23 01:26:57 +00001479 /*TakeArgs=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00001480 ArgType = SubstType(ArgType,
Douglas Gregord6350ae2009-08-28 20:31:08 +00001481 MultiLevelTemplateArgumentList(TemplateArgs),
John McCallce3ff2b2009-08-25 22:02:44 +00001482 TTP->getDefaultArgumentLoc(),
1483 TTP->getDeclName());
Douglas Gregordf667e72009-03-10 20:44:00 +00001484 }
Douglas Gregor99ebf652009-02-27 19:31:52 +00001485
1486 if (ArgType.isNull())
Douglas Gregorcd281c32009-02-28 00:25:32 +00001487 return true;
Douglas Gregor99ebf652009-02-27 19:31:52 +00001488
Douglas Gregor40808ce2009-03-09 23:48:35 +00001489 Arg = TemplateArgument(TTP->getLocation(), ArgType);
Mike Stump1eb44332009-09-09 15:08:12 +00001490 } else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001491 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
1492 if (!NTTP->hasDefaultArgument())
1493 break;
1494
Mike Stump1eb44332009-09-09 15:08:12 +00001495 InstantiatingTemplate Inst(*this, TemplateLoc,
Anders Carlssonfb250522009-06-23 01:26:57 +00001496 Template, Converted.getFlatArguments(),
Anders Carlsson3b56c002009-06-11 16:06:49 +00001497 Converted.flatSize(),
1498 SourceRange(TemplateLoc, RAngleLoc));
Mike Stump1eb44332009-09-09 15:08:12 +00001499
Anders Carlsson3b56c002009-06-11 16:06:49 +00001500 TemplateArgumentList TemplateArgs(Context, Converted,
Anders Carlssonfb250522009-06-23 01:26:57 +00001501 /*TakeArgs=*/false);
Anders Carlsson3b56c002009-06-11 16:06:49 +00001502
Mike Stump1eb44332009-09-09 15:08:12 +00001503 Sema::OwningExprResult E
1504 = SubstExpr(NTTP->getDefaultArgument(),
Douglas Gregord6350ae2009-08-28 20:31:08 +00001505 MultiLevelTemplateArgumentList(TemplateArgs));
Anders Carlsson3b56c002009-06-11 16:06:49 +00001506 if (E.isInvalid())
1507 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001508
Anders Carlsson3b56c002009-06-11 16:06:49 +00001509 Arg = TemplateArgument(E.takeAs<Expr>());
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001510 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00001511 TemplateTemplateParmDecl *TempParm
1512 = cast<TemplateTemplateParmDecl>(*Param);
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001513
1514 if (!TempParm->hasDefaultArgument())
1515 break;
1516
John McCallce3ff2b2009-08-25 22:02:44 +00001517 // FIXME: Subst default argument
Douglas Gregor40808ce2009-03-09 23:48:35 +00001518 Arg = TemplateArgument(TempParm->getDefaultArgument());
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001519 }
1520 } else {
1521 // Retrieve the template argument produced by the user.
Douglas Gregor40808ce2009-03-09 23:48:35 +00001522 Arg = TemplateArgs[ArgIdx];
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001523 }
1524
Douglas Gregorc15cb382009-02-09 23:23:08 +00001525
1526 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
Anders Carlsson0ceffb52009-06-13 02:08:00 +00001527 if (TTP->isParameterPack()) {
Anders Carlssonfb250522009-06-23 01:26:57 +00001528 Converted.BeginPack();
Anders Carlsson0ceffb52009-06-13 02:08:00 +00001529 // Check all the remaining arguments (if any).
1530 for (; ArgIdx < NumArgs; ++ArgIdx) {
1531 if (CheckTemplateTypeArgument(TTP, TemplateArgs[ArgIdx], Converted))
1532 Invalid = true;
1533 }
Mike Stump1eb44332009-09-09 15:08:12 +00001534
Anders Carlssonfb250522009-06-23 01:26:57 +00001535 Converted.EndPack();
Anders Carlsson0ceffb52009-06-13 02:08:00 +00001536 } else {
1537 if (CheckTemplateTypeArgument(TTP, Arg, Converted))
1538 Invalid = true;
1539 }
Mike Stump1eb44332009-09-09 15:08:12 +00001540 } else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregorc15cb382009-02-09 23:23:08 +00001541 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
1542 // Check non-type template parameters.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001543
John McCallce3ff2b2009-08-25 22:02:44 +00001544 // Do substitution on the type of the non-type template parameter
1545 // with the template arguments we've seen thus far.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001546 QualType NTTPType = NTTP->getType();
1547 if (NTTPType->isDependentType()) {
John McCallce3ff2b2009-08-25 22:02:44 +00001548 // Do substitution on the type of the non-type template parameter.
Mike Stump1eb44332009-09-09 15:08:12 +00001549 InstantiatingTemplate Inst(*this, TemplateLoc,
Anders Carlssonfb250522009-06-23 01:26:57 +00001550 Template, Converted.getFlatArguments(),
Anders Carlsson1c5976e2009-06-05 03:43:12 +00001551 Converted.flatSize(),
Douglas Gregordf667e72009-03-10 20:44:00 +00001552 SourceRange(TemplateLoc, RAngleLoc));
1553
Anders Carlssone9c904b2009-06-05 04:47:51 +00001554 TemplateArgumentList TemplateArgs(Context, Converted,
Anders Carlssonfb250522009-06-23 01:26:57 +00001555 /*TakeArgs=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00001556 NTTPType = SubstType(NTTPType,
Douglas Gregor357bbd02009-08-28 20:50:45 +00001557 MultiLevelTemplateArgumentList(TemplateArgs),
John McCallce3ff2b2009-08-25 22:02:44 +00001558 NTTP->getLocation(),
1559 NTTP->getDeclName());
Douglas Gregor2943aed2009-03-03 04:44:36 +00001560 // If that worked, check the non-type template parameter type
1561 // for validity.
1562 if (!NTTPType.isNull())
Mike Stump1eb44332009-09-09 15:08:12 +00001563 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
Douglas Gregor2943aed2009-03-03 04:44:36 +00001564 NTTP->getLocation());
Douglas Gregor2943aed2009-03-03 04:44:36 +00001565 if (NTTPType.isNull()) {
1566 Invalid = true;
1567 break;
1568 }
1569 }
1570
Douglas Gregor40808ce2009-03-09 23:48:35 +00001571 switch (Arg.getKind()) {
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001572 case TemplateArgument::Null:
1573 assert(false && "Should never see a NULL template argument here");
1574 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001575
Douglas Gregor40808ce2009-03-09 23:48:35 +00001576 case TemplateArgument::Expression: {
1577 Expr *E = Arg.getAsExpr();
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001578 TemplateArgument Result;
1579 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
Douglas Gregorc15cb382009-02-09 23:23:08 +00001580 Invalid = true;
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001581 else
Anders Carlssonfb250522009-06-23 01:26:57 +00001582 Converted.Append(Result);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001583 break;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001584 }
1585
Douglas Gregor40808ce2009-03-09 23:48:35 +00001586 case TemplateArgument::Declaration:
1587 case TemplateArgument::Integral:
1588 // We've already checked this template argument, so just copy
1589 // it to the list of converted arguments.
Anders Carlssonfb250522009-06-23 01:26:57 +00001590 Converted.Append(Arg);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001591 break;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001592
Douglas Gregor40808ce2009-03-09 23:48:35 +00001593 case TemplateArgument::Type:
1594 // We have a non-type template parameter but the template
1595 // argument is a type.
Mike Stump1eb44332009-09-09 15:08:12 +00001596
Douglas Gregor40808ce2009-03-09 23:48:35 +00001597 // C++ [temp.arg]p2:
1598 // In a template-argument, an ambiguity between a type-id and
1599 // an expression is resolved to a type-id, regardless of the
1600 // form of the corresponding template-parameter.
1601 //
1602 // We warn specifically about this case, since it can be rather
1603 // confusing for users.
1604 if (Arg.getAsType()->isFunctionType())
1605 Diag(Arg.getLocation(), diag::err_template_arg_nontype_ambig)
1606 << Arg.getAsType();
1607 else
1608 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr);
1609 Diag((*Param)->getLocation(), diag::note_template_param_here);
1610 Invalid = true;
Anders Carlssond01b1da2009-06-15 17:04:53 +00001611 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001612
Anders Carlssond01b1da2009-06-15 17:04:53 +00001613 case TemplateArgument::Pack:
1614 assert(0 && "FIXME: Implement!");
1615 break;
Douglas Gregor40808ce2009-03-09 23:48:35 +00001616 }
Mike Stump1eb44332009-09-09 15:08:12 +00001617 } else {
Douglas Gregorc15cb382009-02-09 23:23:08 +00001618 // Check template template parameters.
Mike Stump1eb44332009-09-09 15:08:12 +00001619 TemplateTemplateParmDecl *TempParm
Douglas Gregorc15cb382009-02-09 23:23:08 +00001620 = cast<TemplateTemplateParmDecl>(*Param);
Mike Stump1eb44332009-09-09 15:08:12 +00001621
Douglas Gregor40808ce2009-03-09 23:48:35 +00001622 switch (Arg.getKind()) {
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001623 case TemplateArgument::Null:
1624 assert(false && "Should never see a NULL template argument here");
1625 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001626
Douglas Gregor40808ce2009-03-09 23:48:35 +00001627 case TemplateArgument::Expression: {
1628 Expr *ArgExpr = Arg.getAsExpr();
1629 if (ArgExpr && isa<DeclRefExpr>(ArgExpr) &&
1630 isa<TemplateDecl>(cast<DeclRefExpr>(ArgExpr)->getDecl())) {
1631 if (CheckTemplateArgument(TempParm, cast<DeclRefExpr>(ArgExpr)))
1632 Invalid = true;
Mike Stump1eb44332009-09-09 15:08:12 +00001633
Douglas Gregor40808ce2009-03-09 23:48:35 +00001634 // Add the converted template argument.
Mike Stump1eb44332009-09-09 15:08:12 +00001635 Decl *D
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00001636 = cast<DeclRefExpr>(ArgExpr)->getDecl()->getCanonicalDecl();
Anders Carlssonfb250522009-06-23 01:26:57 +00001637 Converted.Append(TemplateArgument(Arg.getLocation(), D));
Douglas Gregor40808ce2009-03-09 23:48:35 +00001638 continue;
1639 }
1640 }
1641 // fall through
Mike Stump1eb44332009-09-09 15:08:12 +00001642
Douglas Gregor40808ce2009-03-09 23:48:35 +00001643 case TemplateArgument::Type: {
1644 // We have a template template parameter but the template
1645 // argument does not refer to a template.
1646 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
1647 Invalid = true;
1648 break;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001649 }
1650
Douglas Gregor40808ce2009-03-09 23:48:35 +00001651 case TemplateArgument::Declaration:
1652 // We've already checked this template argument, so just copy
1653 // it to the list of converted arguments.
Anders Carlssonfb250522009-06-23 01:26:57 +00001654 Converted.Append(Arg);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001655 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001656
Douglas Gregor40808ce2009-03-09 23:48:35 +00001657 case TemplateArgument::Integral:
1658 assert(false && "Integral argument with template template parameter");
1659 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001660
Anders Carlssond01b1da2009-06-15 17:04:53 +00001661 case TemplateArgument::Pack:
1662 assert(0 && "FIXME: Implement!");
1663 break;
Douglas Gregor40808ce2009-03-09 23:48:35 +00001664 }
Douglas Gregorc15cb382009-02-09 23:23:08 +00001665 }
1666 }
1667
1668 return Invalid;
1669}
1670
1671/// \brief Check a template argument against its corresponding
1672/// template type parameter.
1673///
1674/// This routine implements the semantics of C++ [temp.arg.type]. It
1675/// returns true if an error occurred, and false otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00001676bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
Douglas Gregorc15cb382009-02-09 23:23:08 +00001677 QualType Arg, SourceLocation ArgLoc) {
1678 // C++ [temp.arg.type]p2:
1679 // A local type, a type with no linkage, an unnamed type or a type
1680 // compounded from any of these types shall not be used as a
1681 // template-argument for a template type-parameter.
1682 //
1683 // FIXME: Perform the recursive and no-linkage type checks.
1684 const TagType *Tag = 0;
John McCall183700f2009-09-21 23:43:11 +00001685 if (const EnumType *EnumT = Arg->getAs<EnumType>())
Douglas Gregorc15cb382009-02-09 23:23:08 +00001686 Tag = EnumT;
Ted Kremenek6217b802009-07-29 21:53:49 +00001687 else if (const RecordType *RecordT = Arg->getAs<RecordType>())
Douglas Gregorc15cb382009-02-09 23:23:08 +00001688 Tag = RecordT;
1689 if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod())
1690 return Diag(ArgLoc, diag::err_template_arg_local_type)
1691 << QualType(Tag, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001692 else if (Tag && !Tag->getDecl()->getDeclName() &&
Douglas Gregor98137532009-03-10 18:33:27 +00001693 !Tag->getDecl()->getTypedefForAnonDecl()) {
Douglas Gregorc15cb382009-02-09 23:23:08 +00001694 Diag(ArgLoc, diag::err_template_arg_unnamed_type);
1695 Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here);
1696 return true;
1697 }
1698
1699 return false;
1700}
1701
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001702/// \brief Checks whether the given template argument is the address
1703/// of an object or function according to C++ [temp.arg.nontype]p1.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001704bool Sema::CheckTemplateArgumentAddressOfObjectOrFunction(Expr *Arg,
1705 NamedDecl *&Entity) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001706 bool Invalid = false;
1707
1708 // See through any implicit casts we added to fix the type.
Eli Friedman73c39ab2009-10-20 08:27:19 +00001709 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001710 Arg = Cast->getSubExpr();
1711
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001712 // C++0x allows nullptr, and there's no further checking to be done for that.
1713 if (Arg->getType()->isNullPtrType())
1714 return false;
1715
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001716 // C++ [temp.arg.nontype]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00001717 //
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001718 // A template-argument for a non-type, non-template
1719 // template-parameter shall be one of: [...]
1720 //
1721 // -- the address of an object or function with external
1722 // linkage, including function templates and function
1723 // template-ids but excluding non-static class members,
1724 // expressed as & id-expression where the & is optional if
1725 // the name refers to a function or array, or if the
1726 // corresponding template-parameter is a reference; or
1727 DeclRefExpr *DRE = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001728
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001729 // Ignore (and complain about) any excess parentheses.
1730 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
1731 if (!Invalid) {
Mike Stump1eb44332009-09-09 15:08:12 +00001732 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001733 diag::err_template_arg_extra_parens)
1734 << Arg->getSourceRange();
1735 Invalid = true;
1736 }
1737
1738 Arg = Parens->getSubExpr();
1739 }
1740
1741 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
1742 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
1743 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
1744 } else
1745 DRE = dyn_cast<DeclRefExpr>(Arg);
1746
1747 if (!DRE || !isa<ValueDecl>(DRE->getDecl()))
Mike Stump1eb44332009-09-09 15:08:12 +00001748 return Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001749 diag::err_template_arg_not_object_or_func_form)
1750 << Arg->getSourceRange();
1751
1752 // Cannot refer to non-static data members
1753 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl()))
1754 return Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
1755 << Field << Arg->getSourceRange();
1756
1757 // Cannot refer to non-static member functions
1758 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
1759 if (!Method->isStatic())
Mike Stump1eb44332009-09-09 15:08:12 +00001760 return Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001761 diag::err_template_arg_method)
1762 << Method << Arg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001763
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001764 // Functions must have external linkage.
1765 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
1766 if (Func->getStorageClass() == FunctionDecl::Static) {
Mike Stump1eb44332009-09-09 15:08:12 +00001767 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001768 diag::err_template_arg_function_not_extern)
1769 << Func << Arg->getSourceRange();
1770 Diag(Func->getLocation(), diag::note_template_arg_internal_object)
1771 << true;
1772 return true;
1773 }
1774
1775 // Okay: we've named a function with external linkage.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001776 Entity = Func;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001777 return Invalid;
1778 }
1779
1780 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
1781 if (!Var->hasGlobalStorage()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001782 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001783 diag::err_template_arg_object_not_extern)
1784 << Var << Arg->getSourceRange();
1785 Diag(Var->getLocation(), diag::note_template_arg_internal_object)
1786 << true;
1787 return true;
1788 }
1789
1790 // Okay: we've named an object with external linkage
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001791 Entity = Var;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001792 return Invalid;
1793 }
Mike Stump1eb44332009-09-09 15:08:12 +00001794
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001795 // We found something else, but we don't know specifically what it is.
Mike Stump1eb44332009-09-09 15:08:12 +00001796 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001797 diag::err_template_arg_not_object_or_func)
1798 << Arg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001799 Diag(DRE->getDecl()->getLocation(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001800 diag::note_template_arg_refers_here);
1801 return true;
1802}
1803
1804/// \brief Checks whether the given template argument is a pointer to
1805/// member constant according to C++ [temp.arg.nontype]p1.
Mike Stump1eb44332009-09-09 15:08:12 +00001806bool
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001807Sema::CheckTemplateArgumentPointerToMember(Expr *Arg, NamedDecl *&Member) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001808 bool Invalid = false;
1809
1810 // See through any implicit casts we added to fix the type.
Eli Friedman73c39ab2009-10-20 08:27:19 +00001811 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001812 Arg = Cast->getSubExpr();
1813
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001814 // C++0x allows nullptr, and there's no further checking to be done for that.
1815 if (Arg->getType()->isNullPtrType())
1816 return false;
1817
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001818 // C++ [temp.arg.nontype]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00001819 //
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001820 // A template-argument for a non-type, non-template
1821 // template-parameter shall be one of: [...]
1822 //
1823 // -- a pointer to member expressed as described in 5.3.1.
1824 QualifiedDeclRefExpr *DRE = 0;
1825
1826 // Ignore (and complain about) any excess parentheses.
1827 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
1828 if (!Invalid) {
Mike Stump1eb44332009-09-09 15:08:12 +00001829 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001830 diag::err_template_arg_extra_parens)
1831 << Arg->getSourceRange();
1832 Invalid = true;
1833 }
1834
1835 Arg = Parens->getSubExpr();
1836 }
1837
1838 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg))
1839 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
1840 DRE = dyn_cast<QualifiedDeclRefExpr>(UnOp->getSubExpr());
1841
1842 if (!DRE)
1843 return Diag(Arg->getSourceRange().getBegin(),
1844 diag::err_template_arg_not_pointer_to_member_form)
1845 << Arg->getSourceRange();
1846
1847 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
1848 assert((isa<FieldDecl>(DRE->getDecl()) ||
1849 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
1850 "Only non-static member pointers can make it here");
1851
1852 // Okay: this is the address of a non-static member, and therefore
1853 // a member pointer constant.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001854 Member = DRE->getDecl();
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001855 return Invalid;
1856 }
1857
1858 // We found something else, but we don't know specifically what it is.
Mike Stump1eb44332009-09-09 15:08:12 +00001859 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001860 diag::err_template_arg_not_pointer_to_member_form)
1861 << Arg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001862 Diag(DRE->getDecl()->getLocation(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001863 diag::note_template_arg_refers_here);
1864 return true;
1865}
1866
Douglas Gregorc15cb382009-02-09 23:23:08 +00001867/// \brief Check a template argument against its corresponding
1868/// non-type template parameter.
1869///
Douglas Gregor2943aed2009-03-03 04:44:36 +00001870/// This routine implements the semantics of C++ [temp.arg.nontype].
1871/// It returns true if an error occurred, and false otherwise. \p
1872/// InstantiatedParamType is the type of the non-type template
1873/// parameter after it has been instantiated.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001874///
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001875/// If no error was detected, Converted receives the converted template argument.
Douglas Gregorc15cb382009-02-09 23:23:08 +00001876bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Mike Stump1eb44332009-09-09 15:08:12 +00001877 QualType InstantiatedParamType, Expr *&Arg,
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001878 TemplateArgument &Converted) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00001879 SourceLocation StartLoc = Arg->getSourceRange().getBegin();
1880
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001881 // If either the parameter has a dependent type or the argument is
1882 // type-dependent, there's nothing we can check now.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001883 // FIXME: Add template argument to Converted!
Douglas Gregor40808ce2009-03-09 23:48:35 +00001884 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
1885 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001886 Converted = TemplateArgument(Arg);
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001887 return false;
Douglas Gregor40808ce2009-03-09 23:48:35 +00001888 }
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001889
1890 // C++ [temp.arg.nontype]p5:
1891 // The following conversions are performed on each expression used
1892 // as a non-type template-argument. If a non-type
1893 // template-argument cannot be converted to the type of the
1894 // corresponding template-parameter then the program is
1895 // ill-formed.
1896 //
1897 // -- for a non-type template-parameter of integral or
1898 // enumeration type, integral promotions (4.5) and integral
1899 // conversions (4.7) are applied.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001900 QualType ParamType = InstantiatedParamType;
Douglas Gregora35284b2009-02-11 00:19:33 +00001901 QualType ArgType = Arg->getType();
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001902 if (ParamType->isIntegralType() || ParamType->isEnumeralType()) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001903 // C++ [temp.arg.nontype]p1:
1904 // A template-argument for a non-type, non-template
1905 // template-parameter shall be one of:
1906 //
1907 // -- an integral constant-expression of integral or enumeration
1908 // type; or
1909 // -- the name of a non-type template-parameter; or
1910 SourceLocation NonConstantLoc;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001911 llvm::APSInt Value;
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001912 if (!ArgType->isIntegralType() && !ArgType->isEnumeralType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001913 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001914 diag::err_template_arg_not_integral_or_enumeral)
1915 << ArgType << Arg->getSourceRange();
1916 Diag(Param->getLocation(), diag::note_template_param_here);
1917 return true;
1918 } else if (!Arg->isValueDependent() &&
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001919 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001920 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
1921 << ArgType << Arg->getSourceRange();
1922 return true;
1923 }
1924
1925 // FIXME: We need some way to more easily get the unqualified form
1926 // of the types without going all the way to the
1927 // canonical type.
1928 if (Context.getCanonicalType(ParamType).getCVRQualifiers())
1929 ParamType = Context.getCanonicalType(ParamType).getUnqualifiedType();
1930 if (Context.getCanonicalType(ArgType).getCVRQualifiers())
1931 ArgType = Context.getCanonicalType(ArgType).getUnqualifiedType();
1932
1933 // Try to convert the argument to the parameter's type.
1934 if (ParamType == ArgType) {
1935 // Okay: no conversion necessary
1936 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
1937 !ParamType->isEnumeralType()) {
1938 // This is an integral promotion or conversion.
Eli Friedman73c39ab2009-10-20 08:27:19 +00001939 ImpCastExprToType(Arg, ParamType, CastExpr::CK_IntegralCast);
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001940 } else {
1941 // We can't perform this conversion.
Mike Stump1eb44332009-09-09 15:08:12 +00001942 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001943 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00001944 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001945 Diag(Param->getLocation(), diag::note_template_param_here);
1946 return true;
1947 }
1948
Douglas Gregorf80a9d52009-03-14 00:20:21 +00001949 QualType IntegerType = Context.getCanonicalType(ParamType);
John McCall183700f2009-09-21 23:43:11 +00001950 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001951 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregorf80a9d52009-03-14 00:20:21 +00001952
1953 if (!Arg->isValueDependent()) {
1954 // Check that an unsigned parameter does not receive a negative
1955 // value.
1956 if (IntegerType->isUnsignedIntegerType()
1957 && (Value.isSigned() && Value.isNegative())) {
1958 Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_negative)
1959 << Value.toString(10) << Param->getType()
1960 << Arg->getSourceRange();
1961 Diag(Param->getLocation(), diag::note_template_param_here);
1962 return true;
1963 }
1964
1965 // Check that we don't overflow the template parameter type.
1966 unsigned AllowedBits = Context.getTypeSize(IntegerType);
1967 if (Value.getActiveBits() > AllowedBits) {
Mike Stump1eb44332009-09-09 15:08:12 +00001968 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorf80a9d52009-03-14 00:20:21 +00001969 diag::err_template_arg_too_large)
1970 << Value.toString(10) << Param->getType()
1971 << Arg->getSourceRange();
1972 Diag(Param->getLocation(), diag::note_template_param_here);
1973 return true;
1974 }
1975
1976 if (Value.getBitWidth() != AllowedBits)
1977 Value.extOrTrunc(AllowedBits);
1978 Value.setIsSigned(IntegerType->isSignedIntegerType());
1979 }
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001980
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001981 // Add the value of this argument to the list of converted
1982 // arguments. We use the bitwidth and signedness of the template
1983 // parameter.
1984 if (Arg->isValueDependent()) {
1985 // The argument is value-dependent. Create a new
1986 // TemplateArgument with the converted expression.
1987 Converted = TemplateArgument(Arg);
1988 return false;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001989 }
1990
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001991 Converted = TemplateArgument(StartLoc, Value,
Mike Stump1eb44332009-09-09 15:08:12 +00001992 ParamType->isEnumeralType() ? ParamType
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001993 : IntegerType);
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001994 return false;
1995 }
Douglas Gregora35284b2009-02-11 00:19:33 +00001996
Douglas Gregorb86b0572009-02-11 01:18:59 +00001997 // Handle pointer-to-function, reference-to-function, and
1998 // pointer-to-member-function all in (roughly) the same way.
1999 if (// -- For a non-type template-parameter of type pointer to
2000 // function, only the function-to-pointer conversion (4.3) is
2001 // applied. If the template-argument represents a set of
2002 // overloaded functions (or a pointer to such), the matching
2003 // function is selected from the set (13.4).
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002004 // In C++0x, any std::nullptr_t value can be converted.
Douglas Gregorb86b0572009-02-11 01:18:59 +00002005 (ParamType->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00002006 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregorb86b0572009-02-11 01:18:59 +00002007 // -- For a non-type template-parameter of type reference to
2008 // function, no conversions apply. If the template-argument
2009 // represents a set of overloaded functions, the matching
2010 // function is selected from the set (13.4).
2011 (ParamType->isReferenceType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00002012 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregorb86b0572009-02-11 01:18:59 +00002013 // -- For a non-type template-parameter of type pointer to
2014 // member function, no conversions apply. If the
2015 // template-argument represents a set of overloaded member
2016 // functions, the matching member function is selected from
2017 // the set (13.4).
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002018 // Again, C++0x allows a std::nullptr_t value.
Douglas Gregorb86b0572009-02-11 01:18:59 +00002019 (ParamType->isMemberPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00002020 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregorb86b0572009-02-11 01:18:59 +00002021 ->isFunctionType())) {
Mike Stump1eb44332009-09-09 15:08:12 +00002022 if (Context.hasSameUnqualifiedType(ArgType,
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002023 ParamType.getNonReferenceType())) {
Douglas Gregora35284b2009-02-11 00:19:33 +00002024 // We don't have to do anything: the types already match.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002025 } else if (ArgType->isNullPtrType() && (ParamType->isPointerType() ||
2026 ParamType->isMemberPointerType())) {
2027 ArgType = ParamType;
Eli Friedman73c39ab2009-10-20 08:27:19 +00002028 if (ParamType->isMemberPointerType())
2029 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NullToMemberPointer);
2030 else
2031 ImpCastExprToType(Arg, ParamType, CastExpr::CK_BitCast);
Douglas Gregorb86b0572009-02-11 01:18:59 +00002032 } else if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregora35284b2009-02-11 00:19:33 +00002033 ArgType = Context.getPointerType(ArgType);
Eli Friedman73c39ab2009-10-20 08:27:19 +00002034 ImpCastExprToType(Arg, ArgType, CastExpr::CK_FunctionToPointerDecay);
Mike Stump1eb44332009-09-09 15:08:12 +00002035 } else if (FunctionDecl *Fn
Douglas Gregora35284b2009-02-11 00:19:33 +00002036 = ResolveAddressOfOverloadedFunction(Arg, ParamType, true)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002037 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
2038 return true;
2039
Anders Carlsson96ad5332009-10-21 17:16:23 +00002040 Arg = FixOverloadedFunctionReference(Arg, Fn);
Douglas Gregora35284b2009-02-11 00:19:33 +00002041 ArgType = Arg->getType();
Douglas Gregorb86b0572009-02-11 01:18:59 +00002042 if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregora35284b2009-02-11 00:19:33 +00002043 ArgType = Context.getPointerType(Arg->getType());
Eli Friedman73c39ab2009-10-20 08:27:19 +00002044 ImpCastExprToType(Arg, ArgType, CastExpr::CK_FunctionToPointerDecay);
Douglas Gregora35284b2009-02-11 00:19:33 +00002045 }
2046 }
2047
Mike Stump1eb44332009-09-09 15:08:12 +00002048 if (!Context.hasSameUnqualifiedType(ArgType,
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002049 ParamType.getNonReferenceType())) {
Douglas Gregora35284b2009-02-11 00:19:33 +00002050 // We can't perform this conversion.
Mike Stump1eb44332009-09-09 15:08:12 +00002051 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregora35284b2009-02-11 00:19:33 +00002052 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00002053 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregora35284b2009-02-11 00:19:33 +00002054 Diag(Param->getLocation(), diag::note_template_param_here);
2055 return true;
2056 }
Mike Stump1eb44332009-09-09 15:08:12 +00002057
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002058 if (ParamType->isMemberPointerType()) {
2059 NamedDecl *Member = 0;
2060 if (CheckTemplateArgumentPointerToMember(Arg, Member))
2061 return true;
2062
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00002063 if (Member)
2064 Member = cast<NamedDecl>(Member->getCanonicalDecl());
Douglas Gregor02cbbd22009-06-11 18:10:32 +00002065 Converted = TemplateArgument(StartLoc, Member);
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002066 return false;
2067 }
Mike Stump1eb44332009-09-09 15:08:12 +00002068
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002069 NamedDecl *Entity = 0;
2070 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2071 return true;
2072
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00002073 if (Entity)
2074 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
Douglas Gregor02cbbd22009-06-11 18:10:32 +00002075 Converted = TemplateArgument(StartLoc, Entity);
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002076 return false;
Douglas Gregora35284b2009-02-11 00:19:33 +00002077 }
2078
Chris Lattnerfe90de72009-02-20 21:37:53 +00002079 if (ParamType->isPointerType()) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00002080 // -- for a non-type template-parameter of type pointer to
2081 // object, qualification conversions (4.4) and the
2082 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002083 // C++0x also allows a value of std::nullptr_t.
Ted Kremenek6217b802009-07-29 21:53:49 +00002084 assert(ParamType->getAs<PointerType>()->getPointeeType()->isObjectType() &&
Douglas Gregorb86b0572009-02-11 01:18:59 +00002085 "Only object pointers allowed here");
Douglas Gregorf684e6e2009-02-11 00:44:29 +00002086
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002087 if (ArgType->isNullPtrType()) {
2088 ArgType = ParamType;
Eli Friedman73c39ab2009-10-20 08:27:19 +00002089 ImpCastExprToType(Arg, ParamType, CastExpr::CK_BitCast);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002090 } else if (ArgType->isArrayType()) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00002091 ArgType = Context.getArrayDecayedType(ArgType);
Eli Friedman73c39ab2009-10-20 08:27:19 +00002092 ImpCastExprToType(Arg, ArgType, CastExpr::CK_ArrayToPointerDecay);
Douglas Gregorf684e6e2009-02-11 00:44:29 +00002093 }
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002094
Douglas Gregorb86b0572009-02-11 01:18:59 +00002095 if (IsQualificationConversion(ArgType, ParamType)) {
2096 ArgType = ParamType;
Eli Friedman73c39ab2009-10-20 08:27:19 +00002097 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NoOp);
Douglas Gregorb86b0572009-02-11 01:18:59 +00002098 }
Mike Stump1eb44332009-09-09 15:08:12 +00002099
Douglas Gregor8e6563b2009-02-11 18:22:40 +00002100 if (!Context.hasSameUnqualifiedType(ArgType, ParamType)) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00002101 // We can't perform this conversion.
Mike Stump1eb44332009-09-09 15:08:12 +00002102 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorb86b0572009-02-11 01:18:59 +00002103 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00002104 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregorb86b0572009-02-11 01:18:59 +00002105 Diag(Param->getLocation(), diag::note_template_param_here);
2106 return true;
2107 }
Mike Stump1eb44332009-09-09 15:08:12 +00002108
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002109 NamedDecl *Entity = 0;
2110 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2111 return true;
2112
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00002113 if (Entity)
2114 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
Douglas Gregor02cbbd22009-06-11 18:10:32 +00002115 Converted = TemplateArgument(StartLoc, Entity);
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002116 return false;
Douglas Gregorf684e6e2009-02-11 00:44:29 +00002117 }
Mike Stump1eb44332009-09-09 15:08:12 +00002118
Ted Kremenek6217b802009-07-29 21:53:49 +00002119 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00002120 // -- For a non-type template-parameter of type reference to
2121 // object, no conversions apply. The type referred to by the
2122 // reference may be more cv-qualified than the (otherwise
2123 // identical) type of the template-argument. The
2124 // template-parameter is bound directly to the
2125 // template-argument, which must be an lvalue.
Douglas Gregorbad0e652009-03-24 20:32:41 +00002126 assert(ParamRefType->getPointeeType()->isObjectType() &&
Douglas Gregorb86b0572009-02-11 01:18:59 +00002127 "Only object references allowed here");
Douglas Gregorf684e6e2009-02-11 00:44:29 +00002128
Douglas Gregor8e6563b2009-02-11 18:22:40 +00002129 if (!Context.hasSameUnqualifiedType(ParamRefType->getPointeeType(), ArgType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002130 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorb86b0572009-02-11 01:18:59 +00002131 diag::err_template_arg_no_ref_bind)
Douglas Gregor2943aed2009-03-03 04:44:36 +00002132 << InstantiatedParamType << Arg->getType()
Douglas Gregorb86b0572009-02-11 01:18:59 +00002133 << Arg->getSourceRange();
2134 Diag(Param->getLocation(), diag::note_template_param_here);
2135 return true;
2136 }
2137
Mike Stump1eb44332009-09-09 15:08:12 +00002138 unsigned ParamQuals
Douglas Gregorb86b0572009-02-11 01:18:59 +00002139 = Context.getCanonicalType(ParamType).getCVRQualifiers();
2140 unsigned ArgQuals = Context.getCanonicalType(ArgType).getCVRQualifiers();
Mike Stump1eb44332009-09-09 15:08:12 +00002141
Douglas Gregorb86b0572009-02-11 01:18:59 +00002142 if ((ParamQuals | ArgQuals) != ParamQuals) {
2143 Diag(Arg->getSourceRange().getBegin(),
2144 diag::err_template_arg_ref_bind_ignores_quals)
Douglas Gregor2943aed2009-03-03 04:44:36 +00002145 << InstantiatedParamType << Arg->getType()
Douglas Gregorb86b0572009-02-11 01:18:59 +00002146 << Arg->getSourceRange();
2147 Diag(Param->getLocation(), diag::note_template_param_here);
2148 return true;
2149 }
Mike Stump1eb44332009-09-09 15:08:12 +00002150
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002151 NamedDecl *Entity = 0;
2152 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2153 return true;
2154
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00002155 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
Douglas Gregor02cbbd22009-06-11 18:10:32 +00002156 Converted = TemplateArgument(StartLoc, Entity);
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002157 return false;
Douglas Gregorb86b0572009-02-11 01:18:59 +00002158 }
Douglas Gregor658bbb52009-02-11 16:16:59 +00002159
2160 // -- For a non-type template-parameter of type pointer to data
2161 // member, qualification conversions (4.4) are applied.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002162 // C++0x allows std::nullptr_t values.
Douglas Gregor658bbb52009-02-11 16:16:59 +00002163 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
2164
Douglas Gregor8e6563b2009-02-11 18:22:40 +00002165 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
Douglas Gregor658bbb52009-02-11 16:16:59 +00002166 // Types match exactly: nothing more to do here.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002167 } else if (ArgType->isNullPtrType()) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00002168 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NullToMemberPointer);
Douglas Gregor658bbb52009-02-11 16:16:59 +00002169 } else if (IsQualificationConversion(ArgType, ParamType)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00002170 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NoOp);
Douglas Gregor658bbb52009-02-11 16:16:59 +00002171 } else {
2172 // We can't perform this conversion.
Mike Stump1eb44332009-09-09 15:08:12 +00002173 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor658bbb52009-02-11 16:16:59 +00002174 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00002175 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor658bbb52009-02-11 16:16:59 +00002176 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump1eb44332009-09-09 15:08:12 +00002177 return true;
Douglas Gregor658bbb52009-02-11 16:16:59 +00002178 }
2179
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002180 NamedDecl *Member = 0;
2181 if (CheckTemplateArgumentPointerToMember(Arg, Member))
2182 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002183
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00002184 if (Member)
2185 Member = cast<NamedDecl>(Member->getCanonicalDecl());
Douglas Gregor02cbbd22009-06-11 18:10:32 +00002186 Converted = TemplateArgument(StartLoc, Member);
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002187 return false;
Douglas Gregorc15cb382009-02-09 23:23:08 +00002188}
2189
2190/// \brief Check a template argument against its corresponding
2191/// template template parameter.
2192///
2193/// This routine implements the semantics of C++ [temp.arg.template].
2194/// It returns true if an error occurred, and false otherwise.
2195bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
2196 DeclRefExpr *Arg) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00002197 assert(isa<TemplateDecl>(Arg->getDecl()) && "Only template decls allowed");
2198 TemplateDecl *Template = cast<TemplateDecl>(Arg->getDecl());
2199
2200 // C++ [temp.arg.template]p1:
2201 // A template-argument for a template template-parameter shall be
2202 // the name of a class template, expressed as id-expression. Only
2203 // primary class templates are considered when matching the
2204 // template template argument with the corresponding parameter;
2205 // partial specializations are not considered even if their
2206 // parameter lists match that of the template template parameter.
Douglas Gregorba1ecb52009-06-12 19:43:02 +00002207 //
2208 // Note that we also allow template template parameters here, which
2209 // will happen when we are dealing with, e.g., class template
2210 // partial specializations.
Mike Stump1eb44332009-09-09 15:08:12 +00002211 if (!isa<ClassTemplateDecl>(Template) &&
Douglas Gregorba1ecb52009-06-12 19:43:02 +00002212 !isa<TemplateTemplateParmDecl>(Template)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002213 assert(isa<FunctionTemplateDecl>(Template) &&
Douglas Gregordd0574e2009-02-10 00:24:35 +00002214 "Only function templates are possible here");
Douglas Gregore53060f2009-06-25 22:08:12 +00002215 Diag(Arg->getLocStart(), diag::err_template_arg_not_class_template);
2216 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
Douglas Gregordd0574e2009-02-10 00:24:35 +00002217 << Template;
2218 }
2219
2220 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
2221 Param->getTemplateParameters(),
2222 true, true,
2223 Arg->getSourceRange().getBegin());
Douglas Gregorc15cb382009-02-09 23:23:08 +00002224}
2225
Douglas Gregorddc29e12009-02-06 22:42:48 +00002226/// \brief Determine whether the given template parameter lists are
2227/// equivalent.
2228///
Mike Stump1eb44332009-09-09 15:08:12 +00002229/// \param New The new template parameter list, typically written in the
Douglas Gregorddc29e12009-02-06 22:42:48 +00002230/// source code as part of a new template declaration.
2231///
2232/// \param Old The old template parameter list, typically found via
2233/// name lookup of the template declared with this template parameter
2234/// list.
2235///
2236/// \param Complain If true, this routine will produce a diagnostic if
2237/// the template parameter lists are not equivalent.
2238///
Douglas Gregordd0574e2009-02-10 00:24:35 +00002239/// \param IsTemplateTemplateParm If true, this routine is being
2240/// called to compare the template parameter lists of a template
2241/// template parameter.
2242///
2243/// \param TemplateArgLoc If this source location is valid, then we
2244/// are actually checking the template parameter list of a template
2245/// argument (New) against the template parameter list of its
2246/// corresponding template template parameter (Old). We produce
2247/// slightly different diagnostics in this scenario.
2248///
Douglas Gregorddc29e12009-02-06 22:42:48 +00002249/// \returns True if the template parameter lists are equal, false
2250/// otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00002251bool
Douglas Gregorddc29e12009-02-06 22:42:48 +00002252Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
2253 TemplateParameterList *Old,
2254 bool Complain,
Douglas Gregordd0574e2009-02-10 00:24:35 +00002255 bool IsTemplateTemplateParm,
2256 SourceLocation TemplateArgLoc) {
Douglas Gregorddc29e12009-02-06 22:42:48 +00002257 if (Old->size() != New->size()) {
2258 if (Complain) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00002259 unsigned NextDiag = diag::err_template_param_list_different_arity;
2260 if (TemplateArgLoc.isValid()) {
2261 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
2262 NextDiag = diag::note_template_param_list_different_arity;
Mike Stump1eb44332009-09-09 15:08:12 +00002263 }
Douglas Gregordd0574e2009-02-10 00:24:35 +00002264 Diag(New->getTemplateLoc(), NextDiag)
2265 << (New->size() > Old->size())
2266 << IsTemplateTemplateParm
2267 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
Douglas Gregorddc29e12009-02-06 22:42:48 +00002268 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
2269 << IsTemplateTemplateParm
2270 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
2271 }
2272
2273 return false;
2274 }
2275
2276 for (TemplateParameterList::iterator OldParm = Old->begin(),
2277 OldParmEnd = Old->end(), NewParm = New->begin();
2278 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
2279 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
Douglas Gregor34d1dc92009-06-24 16:50:40 +00002280 if (Complain) {
2281 unsigned NextDiag = diag::err_template_param_different_kind;
2282 if (TemplateArgLoc.isValid()) {
2283 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
2284 NextDiag = diag::note_template_param_different_kind;
2285 }
2286 Diag((*NewParm)->getLocation(), NextDiag)
2287 << IsTemplateTemplateParm;
2288 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
2289 << IsTemplateTemplateParm;
Douglas Gregordd0574e2009-02-10 00:24:35 +00002290 }
Douglas Gregorddc29e12009-02-06 22:42:48 +00002291 return false;
2292 }
2293
2294 if (isa<TemplateTypeParmDecl>(*OldParm)) {
2295 // Okay; all template type parameters are equivalent (since we
Douglas Gregordd0574e2009-02-10 00:24:35 +00002296 // know we're at the same index).
2297#if 0
Mike Stump390b4cc2009-05-16 07:39:55 +00002298 // FIXME: Enable this code in debug mode *after* we properly go through
2299 // and "instantiate" the template parameter lists of template template
2300 // parameters. It's only after this instantiation that (1) any dependent
2301 // types within the template parameter list of the template template
2302 // parameter can be checked, and (2) the template type parameter depths
Douglas Gregordd0574e2009-02-10 00:24:35 +00002303 // will match up.
Mike Stump1eb44332009-09-09 15:08:12 +00002304 QualType OldParmType
Douglas Gregorddc29e12009-02-06 22:42:48 +00002305 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*OldParm));
Mike Stump1eb44332009-09-09 15:08:12 +00002306 QualType NewParmType
Douglas Gregorddc29e12009-02-06 22:42:48 +00002307 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*NewParm));
Mike Stump1eb44332009-09-09 15:08:12 +00002308 assert(Context.getCanonicalType(OldParmType) ==
2309 Context.getCanonicalType(NewParmType) &&
Douglas Gregorddc29e12009-02-06 22:42:48 +00002310 "type parameter mismatch?");
2311#endif
Mike Stump1eb44332009-09-09 15:08:12 +00002312 } else if (NonTypeTemplateParmDecl *OldNTTP
Douglas Gregorddc29e12009-02-06 22:42:48 +00002313 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
2314 // The types of non-type template parameters must agree.
2315 NonTypeTemplateParmDecl *NewNTTP
2316 = cast<NonTypeTemplateParmDecl>(*NewParm);
2317 if (Context.getCanonicalType(OldNTTP->getType()) !=
2318 Context.getCanonicalType(NewNTTP->getType())) {
2319 if (Complain) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00002320 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
2321 if (TemplateArgLoc.isValid()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002322 Diag(TemplateArgLoc,
Douglas Gregordd0574e2009-02-10 00:24:35 +00002323 diag::err_template_arg_template_params_mismatch);
2324 NextDiag = diag::note_template_nontype_parm_different_type;
2325 }
2326 Diag(NewNTTP->getLocation(), NextDiag)
Douglas Gregorddc29e12009-02-06 22:42:48 +00002327 << NewNTTP->getType()
2328 << IsTemplateTemplateParm;
Mike Stump1eb44332009-09-09 15:08:12 +00002329 Diag(OldNTTP->getLocation(),
Douglas Gregorddc29e12009-02-06 22:42:48 +00002330 diag::note_template_nontype_parm_prev_declaration)
2331 << OldNTTP->getType();
2332 }
2333 return false;
2334 }
2335 } else {
2336 // The template parameter lists of template template
2337 // parameters must agree.
2338 // FIXME: Could we perform a faster "type" comparison here?
Mike Stump1eb44332009-09-09 15:08:12 +00002339 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
Douglas Gregorddc29e12009-02-06 22:42:48 +00002340 "Only template template parameters handled here");
Mike Stump1eb44332009-09-09 15:08:12 +00002341 TemplateTemplateParmDecl *OldTTP
Douglas Gregorddc29e12009-02-06 22:42:48 +00002342 = cast<TemplateTemplateParmDecl>(*OldParm);
2343 TemplateTemplateParmDecl *NewTTP
2344 = cast<TemplateTemplateParmDecl>(*NewParm);
2345 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
2346 OldTTP->getTemplateParameters(),
2347 Complain,
Douglas Gregordd0574e2009-02-10 00:24:35 +00002348 /*IsTemplateTemplateParm=*/true,
2349 TemplateArgLoc))
Douglas Gregorddc29e12009-02-06 22:42:48 +00002350 return false;
2351 }
2352 }
2353
2354 return true;
2355}
2356
2357/// \brief Check whether a template can be declared within this scope.
2358///
2359/// If the template declaration is valid in this scope, returns
2360/// false. Otherwise, issues a diagnostic and returns true.
Mike Stump1eb44332009-09-09 15:08:12 +00002361bool
Douglas Gregor05396e22009-08-25 17:23:04 +00002362Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
Douglas Gregorddc29e12009-02-06 22:42:48 +00002363 // Find the nearest enclosing declaration scope.
2364 while ((S->getFlags() & Scope::DeclScope) == 0 ||
2365 (S->getFlags() & Scope::TemplateParamScope) != 0)
2366 S = S->getParent();
Mike Stump1eb44332009-09-09 15:08:12 +00002367
Douglas Gregorddc29e12009-02-06 22:42:48 +00002368 // C++ [temp]p2:
2369 // A template-declaration can appear only as a namespace scope or
2370 // class scope declaration.
2371 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
Eli Friedman1503f772009-07-31 01:43:05 +00002372 if (Ctx && isa<LinkageSpecDecl>(Ctx) &&
2373 cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
Mike Stump1eb44332009-09-09 15:08:12 +00002374 return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
Douglas Gregor05396e22009-08-25 17:23:04 +00002375 << TemplateParams->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00002376
Eli Friedman1503f772009-07-31 01:43:05 +00002377 while (Ctx && isa<LinkageSpecDecl>(Ctx))
Douglas Gregorddc29e12009-02-06 22:42:48 +00002378 Ctx = Ctx->getParent();
Douglas Gregorddc29e12009-02-06 22:42:48 +00002379
2380 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
2381 return false;
2382
Mike Stump1eb44332009-09-09 15:08:12 +00002383 return Diag(TemplateParams->getTemplateLoc(),
Douglas Gregor05396e22009-08-25 17:23:04 +00002384 diag::err_template_outside_namespace_or_class_scope)
2385 << TemplateParams->getSourceRange();
Douglas Gregorddc29e12009-02-06 22:42:48 +00002386}
Douglas Gregorcc636682009-02-17 23:15:12 +00002387
Douglas Gregord5cb8762009-10-07 00:13:32 +00002388/// \brief Determine what kind of template specialization the given declaration
2389/// is.
2390static TemplateSpecializationKind getTemplateSpecializationKind(NamedDecl *D) {
2391 if (!D)
2392 return TSK_Undeclared;
2393
Douglas Gregorf6b11852009-10-08 15:14:33 +00002394 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
2395 return Record->getTemplateSpecializationKind();
Douglas Gregord5cb8762009-10-07 00:13:32 +00002396 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
2397 return Function->getTemplateSpecializationKind();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002398 if (VarDecl *Var = dyn_cast<VarDecl>(D))
2399 return Var->getTemplateSpecializationKind();
2400
Douglas Gregord5cb8762009-10-07 00:13:32 +00002401 return TSK_Undeclared;
2402}
2403
Douglas Gregor9302da62009-10-14 23:50:59 +00002404/// \brief Check whether a specialization is well-formed in the current
2405/// context.
Douglas Gregor88b70942009-02-25 22:02:03 +00002406///
Douglas Gregor9302da62009-10-14 23:50:59 +00002407/// This routine determines whether a template specialization can be declared
2408/// in the current context (C++ [temp.expl.spec]p2).
Douglas Gregord5cb8762009-10-07 00:13:32 +00002409///
2410/// \param S the semantic analysis object for which this check is being
2411/// performed.
2412///
2413/// \param Specialized the entity being specialized or instantiated, which
2414/// may be a kind of template (class template, function template, etc.) or
2415/// a member of a class template (member function, static data member,
2416/// member class).
2417///
2418/// \param PrevDecl the previous declaration of this entity, if any.
2419///
2420/// \param Loc the location of the explicit specialization or instantiation of
2421/// this entity.
2422///
2423/// \param IsPartialSpecialization whether this is a partial specialization of
2424/// a class template.
2425///
Douglas Gregord5cb8762009-10-07 00:13:32 +00002426/// \returns true if there was an error that we cannot recover from, false
2427/// otherwise.
2428static bool CheckTemplateSpecializationScope(Sema &S,
2429 NamedDecl *Specialized,
2430 NamedDecl *PrevDecl,
2431 SourceLocation Loc,
Douglas Gregor9302da62009-10-14 23:50:59 +00002432 bool IsPartialSpecialization) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00002433 // Keep these "kind" numbers in sync with the %select statements in the
2434 // various diagnostics emitted by this routine.
2435 int EntityKind = 0;
Douglas Gregor1fef4e62009-10-07 22:35:40 +00002436 bool isTemplateSpecialization = false;
2437 if (isa<ClassTemplateDecl>(Specialized)) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00002438 EntityKind = IsPartialSpecialization? 1 : 0;
Douglas Gregor1fef4e62009-10-07 22:35:40 +00002439 isTemplateSpecialization = true;
2440 } else if (isa<FunctionTemplateDecl>(Specialized)) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00002441 EntityKind = 2;
Douglas Gregor1fef4e62009-10-07 22:35:40 +00002442 isTemplateSpecialization = true;
2443 } else if (isa<CXXMethodDecl>(Specialized))
Douglas Gregord5cb8762009-10-07 00:13:32 +00002444 EntityKind = 3;
2445 else if (isa<VarDecl>(Specialized))
2446 EntityKind = 4;
2447 else if (isa<RecordDecl>(Specialized))
2448 EntityKind = 5;
2449 else {
Douglas Gregor9302da62009-10-14 23:50:59 +00002450 S.Diag(Loc, diag::err_template_spec_unknown_kind);
2451 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregord5cb8762009-10-07 00:13:32 +00002452 return true;
2453 }
2454
Douglas Gregor88b70942009-02-25 22:02:03 +00002455 // C++ [temp.expl.spec]p2:
2456 // An explicit specialization shall be declared in the namespace
2457 // of which the template is a member, or, for member templates, in
2458 // the namespace of which the enclosing class or enclosing class
2459 // template is a member. An explicit specialization of a member
2460 // function, member class or static data member of a class
2461 // template shall be declared in the namespace of which the class
2462 // template is a member. Such a declaration may also be a
2463 // definition. If the declaration is not a definition, the
2464 // specialization may be defined later in the name- space in which
2465 // the explicit specialization was declared, or in a namespace
2466 // that encloses the one in which the explicit specialization was
2467 // declared.
Douglas Gregord5cb8762009-10-07 00:13:32 +00002468 if (S.CurContext->getLookupContext()->isFunctionOrMethod()) {
2469 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
Douglas Gregor9302da62009-10-14 23:50:59 +00002470 << Specialized;
Douglas Gregor88b70942009-02-25 22:02:03 +00002471 return true;
2472 }
Douglas Gregor7974c3b2009-10-07 17:21:34 +00002473
Douglas Gregor0a407472009-10-07 17:30:37 +00002474 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
2475 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
Douglas Gregor9302da62009-10-14 23:50:59 +00002476 << Specialized;
Douglas Gregor0a407472009-10-07 17:30:37 +00002477 return true;
2478 }
2479
Douglas Gregor7974c3b2009-10-07 17:21:34 +00002480 // C++ [temp.class.spec]p6:
2481 // A class template partial specialization may be declared or redeclared
2482 // in any namespace scope in which its definition may be defined (14.5.1
2483 // and 14.5.2).
Douglas Gregord5cb8762009-10-07 00:13:32 +00002484 bool ComplainedAboutScope = false;
Douglas Gregor7974c3b2009-10-07 17:21:34 +00002485 DeclContext *SpecializedContext
Douglas Gregord5cb8762009-10-07 00:13:32 +00002486 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregor7974c3b2009-10-07 17:21:34 +00002487 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
Douglas Gregor9302da62009-10-14 23:50:59 +00002488 if ((!PrevDecl ||
2489 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
2490 getTemplateSpecializationKind(PrevDecl) == TSK_ImplicitInstantiation)){
2491 // There is no prior declaration of this entity, so this
2492 // specialization must be in the same context as the template
2493 // itself.
2494 if (!DC->Equals(SpecializedContext)) {
2495 if (isa<TranslationUnitDecl>(SpecializedContext))
2496 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global)
2497 << EntityKind << Specialized;
2498 else if (isa<NamespaceDecl>(SpecializedContext))
2499 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope)
2500 << EntityKind << Specialized
2501 << cast<NamedDecl>(SpecializedContext);
2502
2503 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
2504 ComplainedAboutScope = true;
Douglas Gregor88b70942009-02-25 22:02:03 +00002505 }
Douglas Gregor88b70942009-02-25 22:02:03 +00002506 }
Douglas Gregord5cb8762009-10-07 00:13:32 +00002507
2508 // Make sure that this redeclaration (or definition) occurs in an enclosing
Douglas Gregor9302da62009-10-14 23:50:59 +00002509 // namespace.
Douglas Gregord5cb8762009-10-07 00:13:32 +00002510 // Note that HandleDeclarator() performs this check for explicit
2511 // specializations of function templates, static data members, and member
2512 // functions, so we skip the check here for those kinds of entities.
2513 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
Douglas Gregor7974c3b2009-10-07 17:21:34 +00002514 // Should we refactor that check, so that it occurs later?
2515 if (!ComplainedAboutScope && !DC->Encloses(SpecializedContext) &&
Douglas Gregor9302da62009-10-14 23:50:59 +00002516 !(isa<FunctionTemplateDecl>(Specialized) || isa<VarDecl>(Specialized) ||
2517 isa<FunctionDecl>(Specialized))) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00002518 if (isa<TranslationUnitDecl>(SpecializedContext))
2519 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
2520 << EntityKind << Specialized;
2521 else if (isa<NamespaceDecl>(SpecializedContext))
2522 S.Diag(Loc, diag::err_template_spec_redecl_out_of_scope)
2523 << EntityKind << Specialized
2524 << cast<NamedDecl>(SpecializedContext);
2525
Douglas Gregor9302da62009-10-14 23:50:59 +00002526 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregor88b70942009-02-25 22:02:03 +00002527 }
Douglas Gregord5cb8762009-10-07 00:13:32 +00002528
2529 // FIXME: check for specialization-after-instantiation errors and such.
2530
Douglas Gregor88b70942009-02-25 22:02:03 +00002531 return false;
2532}
Douglas Gregord5cb8762009-10-07 00:13:32 +00002533
Douglas Gregore94866f2009-06-12 21:21:02 +00002534/// \brief Check the non-type template arguments of a class template
2535/// partial specialization according to C++ [temp.class.spec]p9.
2536///
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002537/// \param TemplateParams the template parameters of the primary class
2538/// template.
2539///
2540/// \param TemplateArg the template arguments of the class template
2541/// partial specialization.
2542///
2543/// \param MirrorsPrimaryTemplate will be set true if the class
2544/// template partial specialization arguments are identical to the
2545/// implicit template arguments of the primary template. This is not
2546/// necessarily an error (C++0x), and it is left to the caller to diagnose
2547/// this condition when it is an error.
2548///
Douglas Gregore94866f2009-06-12 21:21:02 +00002549/// \returns true if there was an error, false otherwise.
2550bool Sema::CheckClassTemplatePartialSpecializationArgs(
2551 TemplateParameterList *TemplateParams,
Anders Carlsson6360be72009-06-13 18:20:51 +00002552 const TemplateArgumentListBuilder &TemplateArgs,
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002553 bool &MirrorsPrimaryTemplate) {
Douglas Gregore94866f2009-06-12 21:21:02 +00002554 // FIXME: the interface to this function will have to change to
2555 // accommodate variadic templates.
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002556 MirrorsPrimaryTemplate = true;
Mike Stump1eb44332009-09-09 15:08:12 +00002557
Anders Carlssonfb250522009-06-23 01:26:57 +00002558 const TemplateArgument *ArgList = TemplateArgs.getFlatArguments();
Mike Stump1eb44332009-09-09 15:08:12 +00002559
Douglas Gregore94866f2009-06-12 21:21:02 +00002560 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002561 // Determine whether the template argument list of the partial
2562 // specialization is identical to the implicit argument list of
2563 // the primary template. The caller may need to diagnostic this as
2564 // an error per C++ [temp.class.spec]p9b3.
2565 if (MirrorsPrimaryTemplate) {
Mike Stump1eb44332009-09-09 15:08:12 +00002566 if (TemplateTypeParmDecl *TTP
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002567 = dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(I))) {
2568 if (Context.getCanonicalType(Context.getTypeDeclType(TTP)) !=
Anders Carlsson6360be72009-06-13 18:20:51 +00002569 Context.getCanonicalType(ArgList[I].getAsType()))
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002570 MirrorsPrimaryTemplate = false;
2571 } else if (TemplateTemplateParmDecl *TTP
2572 = dyn_cast<TemplateTemplateParmDecl>(
2573 TemplateParams->getParam(I))) {
2574 // FIXME: We should settle on either Declaration storage or
2575 // Expression storage for template template parameters.
Mike Stump1eb44332009-09-09 15:08:12 +00002576 TemplateTemplateParmDecl *ArgDecl
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002577 = dyn_cast_or_null<TemplateTemplateParmDecl>(
Anders Carlsson6360be72009-06-13 18:20:51 +00002578 ArgList[I].getAsDecl());
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002579 if (!ArgDecl)
Mike Stump1eb44332009-09-09 15:08:12 +00002580 if (DeclRefExpr *DRE
Anders Carlsson6360be72009-06-13 18:20:51 +00002581 = dyn_cast_or_null<DeclRefExpr>(ArgList[I].getAsExpr()))
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002582 ArgDecl = dyn_cast<TemplateTemplateParmDecl>(DRE->getDecl());
2583
2584 if (!ArgDecl ||
2585 ArgDecl->getIndex() != TTP->getIndex() ||
2586 ArgDecl->getDepth() != TTP->getDepth())
2587 MirrorsPrimaryTemplate = false;
2588 }
2589 }
2590
Mike Stump1eb44332009-09-09 15:08:12 +00002591 NonTypeTemplateParmDecl *Param
Douglas Gregore94866f2009-06-12 21:21:02 +00002592 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002593 if (!Param) {
Douglas Gregore94866f2009-06-12 21:21:02 +00002594 continue;
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002595 }
2596
Anders Carlsson6360be72009-06-13 18:20:51 +00002597 Expr *ArgExpr = ArgList[I].getAsExpr();
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002598 if (!ArgExpr) {
2599 MirrorsPrimaryTemplate = false;
Douglas Gregore94866f2009-06-12 21:21:02 +00002600 continue;
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002601 }
Douglas Gregore94866f2009-06-12 21:21:02 +00002602
2603 // C++ [temp.class.spec]p8:
2604 // A non-type argument is non-specialized if it is the name of a
2605 // non-type parameter. All other non-type arguments are
2606 // specialized.
2607 //
2608 // Below, we check the two conditions that only apply to
2609 // specialized non-type arguments, so skip any non-specialized
2610 // arguments.
2611 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Mike Stump1eb44332009-09-09 15:08:12 +00002612 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002613 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl())) {
Mike Stump1eb44332009-09-09 15:08:12 +00002614 if (MirrorsPrimaryTemplate &&
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002615 (Param->getIndex() != NTTP->getIndex() ||
2616 Param->getDepth() != NTTP->getDepth()))
2617 MirrorsPrimaryTemplate = false;
2618
Douglas Gregore94866f2009-06-12 21:21:02 +00002619 continue;
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002620 }
Douglas Gregore94866f2009-06-12 21:21:02 +00002621
2622 // C++ [temp.class.spec]p9:
2623 // Within the argument list of a class template partial
2624 // specialization, the following restrictions apply:
2625 // -- A partially specialized non-type argument expression
2626 // shall not involve a template parameter of the partial
2627 // specialization except when the argument expression is a
2628 // simple identifier.
2629 if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002630 Diag(ArgExpr->getLocStart(),
Douglas Gregore94866f2009-06-12 21:21:02 +00002631 diag::err_dependent_non_type_arg_in_partial_spec)
2632 << ArgExpr->getSourceRange();
2633 return true;
2634 }
2635
2636 // -- The type of a template parameter corresponding to a
2637 // specialized non-type argument shall not be dependent on a
2638 // parameter of the specialization.
2639 if (Param->getType()->isDependentType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002640 Diag(ArgExpr->getLocStart(),
Douglas Gregore94866f2009-06-12 21:21:02 +00002641 diag::err_dependent_typed_non_type_arg_in_partial_spec)
2642 << Param->getType()
2643 << ArgExpr->getSourceRange();
2644 Diag(Param->getLocation(), diag::note_template_param_here);
2645 return true;
2646 }
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002647
2648 MirrorsPrimaryTemplate = false;
Douglas Gregore94866f2009-06-12 21:21:02 +00002649 }
2650
2651 return false;
2652}
2653
Douglas Gregor212e81c2009-03-25 00:13:59 +00002654Sema::DeclResult
John McCall0f434ec2009-07-31 02:45:11 +00002655Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
2656 TagUseKind TUK,
Mike Stump1eb44332009-09-09 15:08:12 +00002657 SourceLocation KWLoc,
Douglas Gregorcc636682009-02-17 23:15:12 +00002658 const CXXScopeSpec &SS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00002659 TemplateTy TemplateD,
Douglas Gregorcc636682009-02-17 23:15:12 +00002660 SourceLocation TemplateNameLoc,
2661 SourceLocation LAngleLoc,
Douglas Gregor40808ce2009-03-09 23:48:35 +00002662 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregorcc636682009-02-17 23:15:12 +00002663 SourceLocation *TemplateArgLocs,
2664 SourceLocation RAngleLoc,
2665 AttributeList *Attr,
2666 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregorfc9cd612009-09-26 20:57:03 +00002667 assert(TUK != TUK_Reference && "References are not specializations");
John McCallf1bbbb42009-09-04 01:14:41 +00002668
Douglas Gregorcc636682009-02-17 23:15:12 +00002669 // Find the class template we're specializing
Douglas Gregor7532dc62009-03-30 22:58:21 +00002670 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump1eb44332009-09-09 15:08:12 +00002671 ClassTemplateDecl *ClassTemplate
Douglas Gregor7532dc62009-03-30 22:58:21 +00002672 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
Douglas Gregorcc636682009-02-17 23:15:12 +00002673
Douglas Gregor1fef4e62009-10-07 22:35:40 +00002674 bool isExplicitSpecialization = false;
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002675 bool isPartialSpecialization = false;
2676
Douglas Gregor88b70942009-02-25 22:02:03 +00002677 // Check the validity of the template headers that introduce this
2678 // template.
Douglas Gregorfc9cd612009-09-26 20:57:03 +00002679 // FIXME: We probably shouldn't complain about these headers for
2680 // friend declarations.
Douglas Gregor05396e22009-08-25 17:23:04 +00002681 TemplateParameterList *TemplateParams
Mike Stump1eb44332009-09-09 15:08:12 +00002682 = MatchTemplateParametersToScopeSpecifier(TemplateNameLoc, SS,
2683 (TemplateParameterList**)TemplateParameterLists.get(),
Douglas Gregor1fef4e62009-10-07 22:35:40 +00002684 TemplateParameterLists.size(),
2685 isExplicitSpecialization);
Douglas Gregor05396e22009-08-25 17:23:04 +00002686 if (TemplateParams && TemplateParams->size() > 0) {
2687 isPartialSpecialization = true;
Douglas Gregor88b70942009-02-25 22:02:03 +00002688
Douglas Gregor05396e22009-08-25 17:23:04 +00002689 // C++ [temp.class.spec]p10:
2690 // The template parameter list of a specialization shall not
2691 // contain default template argument values.
2692 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
2693 Decl *Param = TemplateParams->getParam(I);
2694 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
2695 if (TTP->hasDefaultArgument()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002696 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor05396e22009-08-25 17:23:04 +00002697 diag::err_default_arg_in_partial_spec);
2698 TTP->setDefaultArgument(QualType(), SourceLocation(), false);
2699 }
2700 } else if (NonTypeTemplateParmDecl *NTTP
2701 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2702 if (Expr *DefArg = NTTP->getDefaultArgument()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002703 Diag(NTTP->getDefaultArgumentLoc(),
Douglas Gregor05396e22009-08-25 17:23:04 +00002704 diag::err_default_arg_in_partial_spec)
2705 << DefArg->getSourceRange();
2706 NTTP->setDefaultArgument(0);
2707 DefArg->Destroy(Context);
2708 }
2709 } else {
2710 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
2711 if (Expr *DefArg = TTP->getDefaultArgument()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002712 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor05396e22009-08-25 17:23:04 +00002713 diag::err_default_arg_in_partial_spec)
2714 << DefArg->getSourceRange();
2715 TTP->setDefaultArgument(0);
2716 DefArg->Destroy(Context);
Douglas Gregorba1ecb52009-06-12 19:43:02 +00002717 }
2718 }
2719 }
Douglas Gregora735b202009-10-13 14:39:41 +00002720 } else if (TemplateParams) {
2721 if (TUK == TUK_Friend)
2722 Diag(KWLoc, diag::err_template_spec_friend)
2723 << CodeModificationHint::CreateRemoval(
2724 SourceRange(TemplateParams->getTemplateLoc(),
2725 TemplateParams->getRAngleLoc()))
2726 << SourceRange(LAngleLoc, RAngleLoc);
2727 else
2728 isExplicitSpecialization = true;
2729 } else if (TUK != TUK_Friend) {
Douglas Gregor05396e22009-08-25 17:23:04 +00002730 Diag(KWLoc, diag::err_template_spec_needs_header)
2731 << CodeModificationHint::CreateInsertion(KWLoc, "template<> ");
Douglas Gregor1fef4e62009-10-07 22:35:40 +00002732 isExplicitSpecialization = true;
2733 }
Douglas Gregor88b70942009-02-25 22:02:03 +00002734
Douglas Gregorcc636682009-02-17 23:15:12 +00002735 // Check that the specialization uses the same tag kind as the
2736 // original template.
2737 TagDecl::TagKind Kind;
2738 switch (TagSpec) {
2739 default: assert(0 && "Unknown tag type!");
2740 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2741 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2742 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2743 }
Douglas Gregor501c5ce2009-05-14 16:41:31 +00002744 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump1eb44332009-09-09 15:08:12 +00002745 Kind, KWLoc,
Douglas Gregor501c5ce2009-05-14 16:41:31 +00002746 *ClassTemplate->getIdentifier())) {
Mike Stump1eb44332009-09-09 15:08:12 +00002747 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora3a83512009-04-01 23:51:29 +00002748 << ClassTemplate
Mike Stump1eb44332009-09-09 15:08:12 +00002749 << CodeModificationHint::CreateReplacement(KWLoc,
Douglas Gregora3a83512009-04-01 23:51:29 +00002750 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump1eb44332009-09-09 15:08:12 +00002751 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregorcc636682009-02-17 23:15:12 +00002752 diag::note_previous_use);
2753 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
2754 }
2755
Douglas Gregor40808ce2009-03-09 23:48:35 +00002756 // Translate the parser's template argument list in our AST format.
2757 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
2758 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
2759
Douglas Gregorcc636682009-02-17 23:15:12 +00002760 // Check that the template argument list is well-formed for this
2761 // template.
Anders Carlssonfb250522009-06-23 01:26:57 +00002762 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
2763 TemplateArgs.size());
Mike Stump1eb44332009-09-09 15:08:12 +00002764 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
Anders Carlsson6360be72009-06-13 18:20:51 +00002765 TemplateArgs.data(), TemplateArgs.size(),
Douglas Gregor16134c62009-07-01 00:28:38 +00002766 RAngleLoc, false, Converted))
Douglas Gregor212e81c2009-03-25 00:13:59 +00002767 return true;
Douglas Gregorcc636682009-02-17 23:15:12 +00002768
Mike Stump1eb44332009-09-09 15:08:12 +00002769 assert((Converted.structuredSize() ==
Douglas Gregorcc636682009-02-17 23:15:12 +00002770 ClassTemplate->getTemplateParameters()->size()) &&
2771 "Converted template argument list is too short!");
Mike Stump1eb44332009-09-09 15:08:12 +00002772
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002773 // Find the class template (partial) specialization declaration that
Douglas Gregorcc636682009-02-17 23:15:12 +00002774 // corresponds to these arguments.
2775 llvm::FoldingSetNodeID ID;
Douglas Gregorba1ecb52009-06-12 19:43:02 +00002776 if (isPartialSpecialization) {
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002777 bool MirrorsPrimaryTemplate;
Douglas Gregore94866f2009-06-12 21:21:02 +00002778 if (CheckClassTemplatePartialSpecializationArgs(
2779 ClassTemplate->getTemplateParameters(),
Anders Carlssonfb250522009-06-23 01:26:57 +00002780 Converted, MirrorsPrimaryTemplate))
Douglas Gregore94866f2009-06-12 21:21:02 +00002781 return true;
2782
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002783 if (MirrorsPrimaryTemplate) {
2784 // C++ [temp.class.spec]p9b3:
2785 //
Mike Stump1eb44332009-09-09 15:08:12 +00002786 // -- The argument list of the specialization shall not be identical
2787 // to the implicit argument list of the primary template.
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002788 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
John McCall0f434ec2009-07-31 02:45:11 +00002789 << (TUK == TUK_Definition)
Mike Stump1eb44332009-09-09 15:08:12 +00002790 << CodeModificationHint::CreateRemoval(SourceRange(LAngleLoc,
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002791 RAngleLoc));
John McCall0f434ec2009-07-31 02:45:11 +00002792 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002793 ClassTemplate->getIdentifier(),
2794 TemplateNameLoc,
2795 Attr,
Douglas Gregor05396e22009-08-25 17:23:04 +00002796 TemplateParams,
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002797 AS_none);
2798 }
2799
Douglas Gregorfc9cd612009-09-26 20:57:03 +00002800 // FIXME: Diagnose friend partial specializations
2801
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002802 // FIXME: Template parameter list matters, too
Mike Stump1eb44332009-09-09 15:08:12 +00002803 ClassTemplatePartialSpecializationDecl::Profile(ID,
Anders Carlssonfb250522009-06-23 01:26:57 +00002804 Converted.getFlatArguments(),
Douglas Gregor828e2262009-07-29 16:09:57 +00002805 Converted.flatSize(),
2806 Context);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00002807 } else
Anders Carlsson1c5976e2009-06-05 03:43:12 +00002808 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlssonfb250522009-06-23 01:26:57 +00002809 Converted.getFlatArguments(),
Douglas Gregor828e2262009-07-29 16:09:57 +00002810 Converted.flatSize(),
2811 Context);
Douglas Gregorcc636682009-02-17 23:15:12 +00002812 void *InsertPos = 0;
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002813 ClassTemplateSpecializationDecl *PrevDecl = 0;
2814
2815 if (isPartialSpecialization)
2816 PrevDecl
Mike Stump1eb44332009-09-09 15:08:12 +00002817 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002818 InsertPos);
2819 else
2820 PrevDecl
2821 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorcc636682009-02-17 23:15:12 +00002822
2823 ClassTemplateSpecializationDecl *Specialization = 0;
2824
Douglas Gregor88b70942009-02-25 22:02:03 +00002825 // Check whether we can declare a class template specialization in
2826 // the current scope.
Douglas Gregorfc9cd612009-09-26 20:57:03 +00002827 if (TUK != TUK_Friend &&
Douglas Gregord5cb8762009-10-07 00:13:32 +00002828 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
Douglas Gregor9302da62009-10-14 23:50:59 +00002829 TemplateNameLoc,
2830 isPartialSpecialization))
Douglas Gregor212e81c2009-03-25 00:13:59 +00002831 return true;
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00002832
Douglas Gregorb88e8882009-07-30 17:40:51 +00002833 // The canonical type
2834 QualType CanonType;
Douglas Gregorfc9cd612009-09-26 20:57:03 +00002835 if (PrevDecl &&
2836 (PrevDecl->getSpecializationKind() == TSK_Undeclared ||
2837 TUK == TUK_Friend)) {
Douglas Gregorcc636682009-02-17 23:15:12 +00002838 // Since the only prior class template specialization with these
Douglas Gregorfc9cd612009-09-26 20:57:03 +00002839 // arguments was referenced but not declared, or we're only
2840 // referencing this specialization as a friend, reuse that
Douglas Gregorcc636682009-02-17 23:15:12 +00002841 // declaration node as our own, updating its source location to
2842 // reflect our new declaration.
Douglas Gregorcc636682009-02-17 23:15:12 +00002843 Specialization = PrevDecl;
Douglas Gregor6bc9f7e2009-02-25 22:18:32 +00002844 Specialization->setLocation(TemplateNameLoc);
Douglas Gregorcc636682009-02-17 23:15:12 +00002845 PrevDecl = 0;
Douglas Gregorb88e8882009-07-30 17:40:51 +00002846 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002847 } else if (isPartialSpecialization) {
Douglas Gregorb88e8882009-07-30 17:40:51 +00002848 // Build the canonical type that describes the converted template
2849 // arguments of the class template partial specialization.
2850 CanonType = Context.getTemplateSpecializationType(
2851 TemplateName(ClassTemplate),
2852 Converted.getFlatArguments(),
2853 Converted.flatSize());
2854
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002855 // Create a new class template partial specialization declaration node.
Mike Stump1eb44332009-09-09 15:08:12 +00002856 TemplateParameterList *TemplateParams
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002857 = static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
2858 ClassTemplatePartialSpecializationDecl *PrevPartial
2859 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00002860 ClassTemplatePartialSpecializationDecl *Partial
2861 = ClassTemplatePartialSpecializationDecl::Create(Context,
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002862 ClassTemplate->getDeclContext(),
Anders Carlsson91fdf6f2009-06-05 04:06:48 +00002863 TemplateNameLoc,
2864 TemplateParams,
2865 ClassTemplate,
Anders Carlssonfb250522009-06-23 01:26:57 +00002866 Converted,
Anders Carlsson91fdf6f2009-06-05 04:06:48 +00002867 PrevPartial);
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002868
2869 if (PrevPartial) {
2870 ClassTemplate->getPartialSpecializations().RemoveNode(PrevPartial);
2871 ClassTemplate->getPartialSpecializations().GetOrInsertNode(Partial);
2872 } else {
2873 ClassTemplate->getPartialSpecializations().InsertNode(Partial, InsertPos);
2874 }
2875 Specialization = Partial;
Douglas Gregor031a5882009-06-13 00:26:55 +00002876
2877 // Check that all of the template parameters of the class template
2878 // partial specialization are deducible from the template
2879 // arguments. If not, this class template partial specialization
2880 // will never be used.
2881 llvm::SmallVector<bool, 8> DeducibleParams;
2882 DeducibleParams.resize(TemplateParams->size());
Douglas Gregore73bb602009-09-14 21:25:05 +00002883 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
2884 DeducibleParams);
Douglas Gregor031a5882009-06-13 00:26:55 +00002885 unsigned NumNonDeducible = 0;
2886 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I)
2887 if (!DeducibleParams[I])
2888 ++NumNonDeducible;
2889
2890 if (NumNonDeducible) {
2891 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
2892 << (NumNonDeducible > 1)
2893 << SourceRange(TemplateNameLoc, RAngleLoc);
2894 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
2895 if (!DeducibleParams[I]) {
2896 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
2897 if (Param->getDeclName())
Mike Stump1eb44332009-09-09 15:08:12 +00002898 Diag(Param->getLocation(),
Douglas Gregor031a5882009-06-13 00:26:55 +00002899 diag::note_partial_spec_unused_parameter)
2900 << Param->getDeclName();
2901 else
Mike Stump1eb44332009-09-09 15:08:12 +00002902 Diag(Param->getLocation(),
Douglas Gregor031a5882009-06-13 00:26:55 +00002903 diag::note_partial_spec_unused_parameter)
2904 << std::string("<anonymous>");
2905 }
2906 }
2907 }
Douglas Gregorcc636682009-02-17 23:15:12 +00002908 } else {
2909 // Create a new class template specialization declaration node for
Douglas Gregorfc9cd612009-09-26 20:57:03 +00002910 // this explicit specialization or friend declaration.
Douglas Gregorcc636682009-02-17 23:15:12 +00002911 Specialization
Mike Stump1eb44332009-09-09 15:08:12 +00002912 = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregorcc636682009-02-17 23:15:12 +00002913 ClassTemplate->getDeclContext(),
2914 TemplateNameLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00002915 ClassTemplate,
Anders Carlssonfb250522009-06-23 01:26:57 +00002916 Converted,
Douglas Gregorcc636682009-02-17 23:15:12 +00002917 PrevDecl);
2918
2919 if (PrevDecl) {
2920 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
2921 ClassTemplate->getSpecializations().GetOrInsertNode(Specialization);
2922 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00002923 ClassTemplate->getSpecializations().InsertNode(Specialization,
Douglas Gregorcc636682009-02-17 23:15:12 +00002924 InsertPos);
2925 }
Douglas Gregorb88e8882009-07-30 17:40:51 +00002926
2927 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregorcc636682009-02-17 23:15:12 +00002928 }
2929
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00002930 // C++ [temp.expl.spec]p6:
2931 // If a template, a member template or the member of a class template is
2932 // explicitly specialized then that specialization shall be declared
2933 // before the first use of that specialization that would cause an implicit
2934 // instantiation to take place, in every translation unit in which such a
2935 // use occurs; no diagnostic is required.
2936 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
2937 SourceRange Range(TemplateNameLoc, RAngleLoc);
2938 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
2939 << Context.getTypeDeclType(Specialization) << Range;
2940
2941 Diag(PrevDecl->getPointOfInstantiation(),
2942 diag::note_instantiation_required_here)
2943 << (PrevDecl->getTemplateSpecializationKind()
2944 != TSK_ImplicitInstantiation);
2945 return true;
2946 }
2947
Douglas Gregorfc9cd612009-09-26 20:57:03 +00002948 // If this is not a friend, note that this is an explicit specialization.
2949 if (TUK != TUK_Friend)
2950 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregorcc636682009-02-17 23:15:12 +00002951
2952 // Check that this isn't a redefinition of this specialization.
John McCall0f434ec2009-07-31 02:45:11 +00002953 if (TUK == TUK_Definition) {
Douglas Gregorcc636682009-02-17 23:15:12 +00002954 if (RecordDecl *Def = Specialization->getDefinition(Context)) {
Douglas Gregorcc636682009-02-17 23:15:12 +00002955 SourceRange Range(TemplateNameLoc, RAngleLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00002956 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002957 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregorcc636682009-02-17 23:15:12 +00002958 Diag(Def->getLocation(), diag::note_previous_definition);
2959 Specialization->setInvalidDecl();
Douglas Gregor212e81c2009-03-25 00:13:59 +00002960 return true;
Douglas Gregorcc636682009-02-17 23:15:12 +00002961 }
2962 }
2963
Douglas Gregorfc705b82009-02-26 22:19:44 +00002964 // Build the fully-sugared type for this class template
2965 // specialization as the user wrote in the specialization
2966 // itself. This means that we'll pretty-print the type retrieved
2967 // from the specialization's declaration the way that the user
2968 // actually wrote the specialization, rather than formatting the
2969 // name based on the "canonical" representation used to store the
2970 // template arguments in the specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00002971 QualType WrittenTy
2972 = Context.getTemplateSpecializationType(Name,
Anders Carlsson6360be72009-06-13 18:20:51 +00002973 TemplateArgs.data(),
Douglas Gregor7532dc62009-03-30 22:58:21 +00002974 TemplateArgs.size(),
Douglas Gregorb88e8882009-07-30 17:40:51 +00002975 CanonType);
Douglas Gregorfc9cd612009-09-26 20:57:03 +00002976 if (TUK != TUK_Friend)
2977 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregor40808ce2009-03-09 23:48:35 +00002978 TemplateArgsIn.release();
Douglas Gregorcc636682009-02-17 23:15:12 +00002979
Douglas Gregor6bc9f7e2009-02-25 22:18:32 +00002980 // C++ [temp.expl.spec]p9:
2981 // A template explicit specialization is in the scope of the
2982 // namespace in which the template was defined.
2983 //
2984 // We actually implement this paragraph where we set the semantic
2985 // context (in the creation of the ClassTemplateSpecializationDecl),
2986 // but we also maintain the lexical context where the actual
2987 // definition occurs.
Douglas Gregorcc636682009-02-17 23:15:12 +00002988 Specialization->setLexicalDeclContext(CurContext);
Mike Stump1eb44332009-09-09 15:08:12 +00002989
Douglas Gregorcc636682009-02-17 23:15:12 +00002990 // We may be starting the definition of this specialization.
John McCall0f434ec2009-07-31 02:45:11 +00002991 if (TUK == TUK_Definition)
Douglas Gregorcc636682009-02-17 23:15:12 +00002992 Specialization->startDefinition();
2993
Douglas Gregorfc9cd612009-09-26 20:57:03 +00002994 if (TUK == TUK_Friend) {
2995 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
2996 TemplateNameLoc,
2997 WrittenTy.getTypePtr(),
2998 /*FIXME:*/KWLoc);
2999 Friend->setAccess(AS_public);
3000 CurContext->addDecl(Friend);
3001 } else {
3002 // Add the specialization into its lexical context, so that it can
3003 // be seen when iterating through the list of declarations in that
3004 // context. However, specializations are not found by name lookup.
3005 CurContext->addDecl(Specialization);
3006 }
Chris Lattnerb28317a2009-03-28 19:18:32 +00003007 return DeclPtrTy::make(Specialization);
Douglas Gregorcc636682009-02-17 23:15:12 +00003008}
Douglas Gregord57959a2009-03-27 23:10:48 +00003009
Mike Stump1eb44332009-09-09 15:08:12 +00003010Sema::DeclPtrTy
3011Sema::ActOnTemplateDeclarator(Scope *S,
Douglas Gregore542c862009-06-23 23:11:28 +00003012 MultiTemplateParamsArg TemplateParameterLists,
3013 Declarator &D) {
3014 return HandleDeclarator(S, D, move(TemplateParameterLists), false);
3015}
3016
Mike Stump1eb44332009-09-09 15:08:12 +00003017Sema::DeclPtrTy
3018Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
Douglas Gregor52591bf2009-06-24 00:54:41 +00003019 MultiTemplateParamsArg TemplateParameterLists,
3020 Declarator &D) {
3021 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
3022 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
3023 "Not a function declarator!");
3024 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Mike Stump1eb44332009-09-09 15:08:12 +00003025
Douglas Gregor52591bf2009-06-24 00:54:41 +00003026 if (FTI.hasPrototype) {
Mike Stump1eb44332009-09-09 15:08:12 +00003027 // FIXME: Diagnose arguments without names in C.
Douglas Gregor52591bf2009-06-24 00:54:41 +00003028 }
Mike Stump1eb44332009-09-09 15:08:12 +00003029
Douglas Gregor52591bf2009-06-24 00:54:41 +00003030 Scope *ParentScope = FnBodyScope->getParent();
Mike Stump1eb44332009-09-09 15:08:12 +00003031
3032 DeclPtrTy DP = HandleDeclarator(ParentScope, D,
Douglas Gregor52591bf2009-06-24 00:54:41 +00003033 move(TemplateParameterLists),
3034 /*IsFunctionDefinition=*/true);
Mike Stump1eb44332009-09-09 15:08:12 +00003035 if (FunctionTemplateDecl *FunctionTemplate
Douglas Gregorf59a56e2009-07-21 23:53:31 +00003036 = dyn_cast_or_null<FunctionTemplateDecl>(DP.getAs<Decl>()))
Mike Stump1eb44332009-09-09 15:08:12 +00003037 return ActOnStartOfFunctionDef(FnBodyScope,
Douglas Gregore53060f2009-06-25 22:08:12 +00003038 DeclPtrTy::make(FunctionTemplate->getTemplatedDecl()));
Douglas Gregorf59a56e2009-07-21 23:53:31 +00003039 if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(DP.getAs<Decl>()))
3040 return ActOnStartOfFunctionDef(FnBodyScope, DeclPtrTy::make(Function));
Douglas Gregore53060f2009-06-25 22:08:12 +00003041 return DeclPtrTy();
Douglas Gregor52591bf2009-06-24 00:54:41 +00003042}
3043
Douglas Gregor454885e2009-10-15 15:54:05 +00003044/// \brief Diagnose cases where we have an explicit template specialization
3045/// before/after an explicit template instantiation, producing diagnostics
3046/// for those cases where they are required and determining whether the
3047/// new specialization/instantiation will have any effect.
3048///
3049/// \param S the semantic analysis object.
3050///
3051/// \param NewLoc the location of the new explicit specialization or
3052/// instantiation.
3053///
3054/// \param NewTSK the kind of the new explicit specialization or instantiation.
3055///
3056/// \param PrevDecl the previous declaration of the entity.
3057///
3058/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
3059///
3060/// \param PrevPointOfInstantiation if valid, indicates where the previus
3061/// declaration was instantiated (either implicitly or explicitly).
3062///
3063/// \param SuppressNew will be set to true to indicate that the new
3064/// specialization or instantiation has no effect and should be ignored.
3065///
3066/// \returns true if there was an error that should prevent the introduction of
3067/// the new declaration into the AST, false otherwise.
3068static bool
3069CheckSpecializationInstantiationRedecl(Sema &S,
3070 SourceLocation NewLoc,
3071 TemplateSpecializationKind NewTSK,
3072 NamedDecl *PrevDecl,
3073 TemplateSpecializationKind PrevTSK,
3074 SourceLocation PrevPointOfInstantiation,
3075 bool &SuppressNew) {
3076 SuppressNew = false;
3077
3078 switch (NewTSK) {
3079 case TSK_Undeclared:
3080 case TSK_ImplicitInstantiation:
3081 assert(false && "Don't check implicit instantiations here");
3082 return false;
3083
3084 case TSK_ExplicitSpecialization:
3085 switch (PrevTSK) {
3086 case TSK_Undeclared:
3087 case TSK_ExplicitSpecialization:
3088 // Okay, we're just specializing something that is either already
3089 // explicitly specialized or has merely been mentioned without any
3090 // instantiation.
3091 return false;
3092
3093 case TSK_ImplicitInstantiation:
3094 if (PrevPointOfInstantiation.isInvalid()) {
3095 // The declaration itself has not actually been instantiated, so it is
3096 // still okay to specialize it.
3097 return false;
3098 }
3099 // Fall through
3100
3101 case TSK_ExplicitInstantiationDeclaration:
3102 case TSK_ExplicitInstantiationDefinition:
3103 assert((PrevTSK == TSK_ImplicitInstantiation ||
3104 PrevPointOfInstantiation.isValid()) &&
3105 "Explicit instantiation without point of instantiation?");
3106
3107 // C++ [temp.expl.spec]p6:
3108 // If a template, a member template or the member of a class template
3109 // is explicitly specialized then that specialization shall be declared
3110 // before the first use of that specialization that would cause an
3111 // implicit instantiation to take place, in every translation unit in
3112 // which such a use occurs; no diagnostic is required.
3113 S.Diag(NewLoc, diag::err_specialization_after_instantiation)
3114 << PrevDecl;
3115 S.Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
3116 << (PrevTSK != TSK_ImplicitInstantiation);
3117
3118 return true;
3119 }
3120 break;
3121
3122 case TSK_ExplicitInstantiationDeclaration:
3123 switch (PrevTSK) {
3124 case TSK_ExplicitInstantiationDeclaration:
3125 // This explicit instantiation declaration is redundant (that's okay).
3126 SuppressNew = true;
3127 return false;
3128
3129 case TSK_Undeclared:
3130 case TSK_ImplicitInstantiation:
3131 // We're explicitly instantiating something that may have already been
3132 // implicitly instantiated; that's fine.
3133 return false;
3134
3135 case TSK_ExplicitSpecialization:
3136 // C++0x [temp.explicit]p4:
3137 // For a given set of template parameters, if an explicit instantiation
3138 // of a template appears after a declaration of an explicit
3139 // specialization for that template, the explicit instantiation has no
3140 // effect.
3141 return false;
3142
3143 case TSK_ExplicitInstantiationDefinition:
3144 // C++0x [temp.explicit]p10:
3145 // If an entity is the subject of both an explicit instantiation
3146 // declaration and an explicit instantiation definition in the same
3147 // translation unit, the definition shall follow the declaration.
3148 S.Diag(NewLoc,
3149 diag::err_explicit_instantiation_declaration_after_definition);
3150 S.Diag(PrevPointOfInstantiation,
3151 diag::note_explicit_instantiation_definition_here);
3152 assert(PrevPointOfInstantiation.isValid() &&
3153 "Explicit instantiation without point of instantiation?");
3154 SuppressNew = true;
3155 return false;
3156 }
3157 break;
3158
3159 case TSK_ExplicitInstantiationDefinition:
3160 switch (PrevTSK) {
3161 case TSK_Undeclared:
3162 case TSK_ImplicitInstantiation:
3163 // We're explicitly instantiating something that may have already been
3164 // implicitly instantiated; that's fine.
3165 return false;
3166
3167 case TSK_ExplicitSpecialization:
3168 // C++ DR 259, C++0x [temp.explicit]p4:
3169 // For a given set of template parameters, if an explicit
3170 // instantiation of a template appears after a declaration of
3171 // an explicit specialization for that template, the explicit
3172 // instantiation has no effect.
3173 //
3174 // In C++98/03 mode, we only give an extension warning here, because it
3175 // is not not harmful to try to explicitly instantiate something that
3176 // has been explicitly specialized.
3177 if (!S.getLangOptions().CPlusPlus0x) {
3178 S.Diag(NewLoc, diag::ext_explicit_instantiation_after_specialization)
3179 << PrevDecl;
3180 S.Diag(PrevDecl->getLocation(),
3181 diag::note_previous_template_specialization);
3182 }
3183 SuppressNew = true;
3184 return false;
3185
3186 case TSK_ExplicitInstantiationDeclaration:
3187 // We're explicity instantiating a definition for something for which we
3188 // were previously asked to suppress instantiations. That's fine.
3189 return false;
3190
3191 case TSK_ExplicitInstantiationDefinition:
3192 // C++0x [temp.spec]p5:
3193 // For a given template and a given set of template-arguments,
3194 // - an explicit instantiation definition shall appear at most once
3195 // in a program,
3196 S.Diag(NewLoc, diag::err_explicit_instantiation_duplicate)
3197 << PrevDecl;
3198 S.Diag(PrevPointOfInstantiation,
3199 diag::note_previous_explicit_instantiation);
3200 SuppressNew = true;
3201 return false;
3202 }
3203 break;
3204 }
3205
3206 assert(false && "Missing specialization/instantiation case?");
3207
3208 return false;
3209}
3210
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00003211/// \brief Perform semantic analysis for the given function template
3212/// specialization.
3213///
3214/// This routine performs all of the semantic analysis required for an
3215/// explicit function template specialization. On successful completion,
3216/// the function declaration \p FD will become a function template
3217/// specialization.
3218///
3219/// \param FD the function declaration, which will be updated to become a
3220/// function template specialization.
3221///
3222/// \param HasExplicitTemplateArgs whether any template arguments were
3223/// explicitly provided.
3224///
3225/// \param LAngleLoc the location of the left angle bracket ('<'), if
3226/// template arguments were explicitly provided.
3227///
3228/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
3229/// if any.
3230///
3231/// \param NumExplicitTemplateArgs the number of explicitly-provided template
3232/// arguments. This number may be zero even when HasExplicitTemplateArgs is
3233/// true as in, e.g., \c void sort<>(char*, char*);
3234///
3235/// \param RAngleLoc the location of the right angle bracket ('>'), if
3236/// template arguments were explicitly provided.
3237///
3238/// \param PrevDecl the set of declarations that
3239bool
3240Sema::CheckFunctionTemplateSpecialization(FunctionDecl *FD,
3241 bool HasExplicitTemplateArgs,
3242 SourceLocation LAngleLoc,
3243 const TemplateArgument *ExplicitTemplateArgs,
3244 unsigned NumExplicitTemplateArgs,
3245 SourceLocation RAngleLoc,
3246 NamedDecl *&PrevDecl) {
3247 // The set of function template specializations that could match this
3248 // explicit function template specialization.
3249 typedef llvm::SmallVector<FunctionDecl *, 8> CandidateSet;
3250 CandidateSet Candidates;
3251
3252 DeclContext *FDLookupContext = FD->getDeclContext()->getLookupContext();
3253 for (OverloadIterator Ovl(PrevDecl), OvlEnd; Ovl != OvlEnd; ++Ovl) {
3254 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(*Ovl)) {
3255 // Only consider templates found within the same semantic lookup scope as
3256 // FD.
3257 if (!FDLookupContext->Equals(Ovl->getDeclContext()->getLookupContext()))
3258 continue;
3259
3260 // C++ [temp.expl.spec]p11:
3261 // A trailing template-argument can be left unspecified in the
3262 // template-id naming an explicit function template specialization
3263 // provided it can be deduced from the function argument type.
3264 // Perform template argument deduction to determine whether we may be
3265 // specializing this template.
3266 // FIXME: It is somewhat wasteful to build
3267 TemplateDeductionInfo Info(Context);
3268 FunctionDecl *Specialization = 0;
3269 if (TemplateDeductionResult TDK
3270 = DeduceTemplateArguments(FunTmpl, HasExplicitTemplateArgs,
3271 ExplicitTemplateArgs,
3272 NumExplicitTemplateArgs,
3273 FD->getType(),
3274 Specialization,
3275 Info)) {
3276 // FIXME: Template argument deduction failed; record why it failed, so
3277 // that we can provide nifty diagnostics.
3278 (void)TDK;
3279 continue;
3280 }
3281
3282 // Record this candidate.
3283 Candidates.push_back(Specialization);
3284 }
3285 }
3286
Douglas Gregorc5df30f2009-09-26 03:41:46 +00003287 // Find the most specialized function template.
3288 FunctionDecl *Specialization = getMostSpecialized(Candidates.data(),
3289 Candidates.size(),
3290 TPOC_Other,
3291 FD->getLocation(),
3292 PartialDiagnostic(diag::err_function_template_spec_no_match)
3293 << FD->getDeclName(),
3294 PartialDiagnostic(diag::err_function_template_spec_ambiguous)
3295 << FD->getDeclName() << HasExplicitTemplateArgs,
3296 PartialDiagnostic(diag::note_function_template_spec_matched));
3297 if (!Specialization)
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00003298 return true;
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00003299
3300 // FIXME: Check if the prior specialization has a point of instantiation.
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003301 // If so, we have run afoul of .
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00003302
Douglas Gregord5cb8762009-10-07 00:13:32 +00003303 // Check the scope of this explicit specialization.
3304 if (CheckTemplateSpecializationScope(*this,
3305 Specialization->getPrimaryTemplate(),
3306 Specialization, FD->getLocation(),
Douglas Gregor9302da62009-10-14 23:50:59 +00003307 false))
Douglas Gregord5cb8762009-10-07 00:13:32 +00003308 return true;
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003309
3310 // C++ [temp.expl.spec]p6:
3311 // If a template, a member template or the member of a class template is
3312 // explicitly specialized then that spe- cialization shall be declared
3313 // before the first use of that specialization that would cause an implicit
3314 // instantiation to take place, in every translation unit in which such a
3315 // use occurs; no diagnostic is required.
3316 FunctionTemplateSpecializationInfo *SpecInfo
3317 = Specialization->getTemplateSpecializationInfo();
3318 assert(SpecInfo && "Function template specialization info missing?");
3319 if (SpecInfo->getPointOfInstantiation().isValid()) {
3320 Diag(FD->getLocation(), diag::err_specialization_after_instantiation)
3321 << FD;
3322 Diag(SpecInfo->getPointOfInstantiation(),
3323 diag::note_instantiation_required_here)
3324 << (Specialization->getTemplateSpecializationKind()
3325 != TSK_ImplicitInstantiation);
3326 return true;
3327 }
Douglas Gregord5cb8762009-10-07 00:13:32 +00003328
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00003329 // Mark the prior declaration as an explicit specialization, so that later
3330 // clients know that this is an explicit specialization.
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003331 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00003332
3333 // Turn the given function declaration into a function template
3334 // specialization, with the template arguments from the previous
3335 // specialization.
3336 FD->setFunctionTemplateSpecialization(Context,
3337 Specialization->getPrimaryTemplate(),
3338 new (Context) TemplateArgumentList(
3339 *Specialization->getTemplateSpecializationArgs()),
3340 /*InsertPos=*/0,
3341 TSK_ExplicitSpecialization);
3342
3343 // The "previous declaration" for this function template specialization is
3344 // the prior function template specialization.
3345 PrevDecl = Specialization;
3346 return false;
3347}
3348
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003349/// \brief Perform semantic analysis for the given non-template member
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003350/// specialization.
3351///
3352/// This routine performs all of the semantic analysis required for an
3353/// explicit member function specialization. On successful completion,
3354/// the function declaration \p FD will become a member function
3355/// specialization.
3356///
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003357/// \param Member the member declaration, which will be updated to become a
3358/// specialization.
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003359///
3360/// \param PrevDecl the set of declarations, one of which may be specialized
3361/// by this function specialization.
3362bool
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003363Sema::CheckMemberSpecialization(NamedDecl *Member, NamedDecl *&PrevDecl) {
3364 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
3365
3366 // Try to find the member we are instantiating.
3367 NamedDecl *Instantiation = 0;
3368 NamedDecl *InstantiatedFrom = 0;
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003369 MemberSpecializationInfo *MSInfo = 0;
3370
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003371 if (!PrevDecl) {
3372 // Nowhere to look anyway.
3373 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
3374 for (OverloadIterator Ovl(PrevDecl), OvlEnd; Ovl != OvlEnd; ++Ovl) {
3375 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*Ovl)) {
3376 if (Context.hasSameType(Function->getType(), Method->getType())) {
3377 Instantiation = Method;
3378 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003379 MSInfo = Method->getMemberSpecializationInfo();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003380 break;
3381 }
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003382 }
3383 }
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003384 } else if (isa<VarDecl>(Member)) {
3385 if (VarDecl *PrevVar = dyn_cast<VarDecl>(PrevDecl))
3386 if (PrevVar->isStaticDataMember()) {
3387 Instantiation = PrevDecl;
3388 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003389 MSInfo = PrevVar->getMemberSpecializationInfo();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003390 }
3391 } else if (isa<RecordDecl>(Member)) {
3392 if (CXXRecordDecl *PrevRecord = dyn_cast<CXXRecordDecl>(PrevDecl)) {
3393 Instantiation = PrevDecl;
3394 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003395 MSInfo = PrevRecord->getMemberSpecializationInfo();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003396 }
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003397 }
3398
3399 if (!Instantiation) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003400 // There is no previous declaration that matches. Since member
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003401 // specializations are always out-of-line, the caller will complain about
3402 // this mismatch later.
3403 return false;
3404 }
3405
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003406 // Make sure that this is a specialization of a member.
3407 if (!InstantiatedFrom) {
3408 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
3409 << Member;
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003410 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
3411 return true;
3412 }
3413
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003414 // C++ [temp.expl.spec]p6:
3415 // If a template, a member template or the member of a class template is
3416 // explicitly specialized then that spe- cialization shall be declared
3417 // before the first use of that specialization that would cause an implicit
3418 // instantiation to take place, in every translation unit in which such a
3419 // use occurs; no diagnostic is required.
3420 assert(MSInfo && "Member specialization info missing?");
3421 if (MSInfo->getPointOfInstantiation().isValid()) {
3422 Diag(Member->getLocation(), diag::err_specialization_after_instantiation)
3423 << Member;
3424 Diag(MSInfo->getPointOfInstantiation(),
3425 diag::note_instantiation_required_here)
3426 << (MSInfo->getTemplateSpecializationKind() != TSK_ImplicitInstantiation);
3427 return true;
3428 }
3429
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003430 // Check the scope of this explicit specialization.
3431 if (CheckTemplateSpecializationScope(*this,
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003432 InstantiatedFrom,
3433 Instantiation, Member->getLocation(),
Douglas Gregor9302da62009-10-14 23:50:59 +00003434 false))
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003435 return true;
Douglas Gregor2db32322009-10-07 23:56:10 +00003436
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003437 // Note that this is an explicit instantiation of a member.
Douglas Gregorf6b11852009-10-08 15:14:33 +00003438 // the original declaration to note that it is an explicit specialization
3439 // (if it was previously an implicit instantiation). This latter step
3440 // makes bookkeeping easier.
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003441 if (isa<FunctionDecl>(Member)) {
Douglas Gregorf6b11852009-10-08 15:14:33 +00003442 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
3443 if (InstantiationFunction->getTemplateSpecializationKind() ==
3444 TSK_ImplicitInstantiation) {
3445 InstantiationFunction->setTemplateSpecializationKind(
3446 TSK_ExplicitSpecialization);
3447 InstantiationFunction->setLocation(Member->getLocation());
3448 }
3449
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003450 cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
3451 cast<CXXMethodDecl>(InstantiatedFrom),
3452 TSK_ExplicitSpecialization);
3453 } else if (isa<VarDecl>(Member)) {
Douglas Gregorf6b11852009-10-08 15:14:33 +00003454 VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
3455 if (InstantiationVar->getTemplateSpecializationKind() ==
3456 TSK_ImplicitInstantiation) {
3457 InstantiationVar->setTemplateSpecializationKind(
3458 TSK_ExplicitSpecialization);
3459 InstantiationVar->setLocation(Member->getLocation());
3460 }
3461
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003462 Context.setInstantiatedFromStaticDataMember(cast<VarDecl>(Member),
3463 cast<VarDecl>(InstantiatedFrom),
3464 TSK_ExplicitSpecialization);
3465 } else {
3466 assert(isa<CXXRecordDecl>(Member) && "Only member classes remain");
Douglas Gregorf6b11852009-10-08 15:14:33 +00003467 CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
3468 if (InstantiationClass->getTemplateSpecializationKind() ==
3469 TSK_ImplicitInstantiation) {
3470 InstantiationClass->setTemplateSpecializationKind(
3471 TSK_ExplicitSpecialization);
3472 InstantiationClass->setLocation(Member->getLocation());
3473 }
3474
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003475 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
Douglas Gregorf6b11852009-10-08 15:14:33 +00003476 cast<CXXRecordDecl>(InstantiatedFrom),
3477 TSK_ExplicitSpecialization);
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003478 }
3479
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003480 // Save the caller the trouble of having to figure out which declaration
3481 // this specialization matches.
3482 PrevDecl = Instantiation;
3483 return false;
3484}
3485
Douglas Gregor558c0322009-10-14 23:41:34 +00003486/// \brief Check the scope of an explicit instantiation.
3487static void CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
3488 SourceLocation InstLoc,
3489 bool WasQualifiedName) {
3490 DeclContext *ExpectedContext
3491 = D->getDeclContext()->getEnclosingNamespaceContext()->getLookupContext();
3492 DeclContext *CurContext = S.CurContext->getLookupContext();
3493
3494 // C++0x [temp.explicit]p2:
3495 // An explicit instantiation shall appear in an enclosing namespace of its
3496 // template.
3497 //
3498 // This is DR275, which we do not retroactively apply to C++98/03.
3499 if (S.getLangOptions().CPlusPlus0x &&
3500 !CurContext->Encloses(ExpectedContext)) {
3501 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ExpectedContext))
3502 S.Diag(InstLoc, diag::err_explicit_instantiation_out_of_scope)
3503 << D << NS;
3504 else
3505 S.Diag(InstLoc, diag::err_explicit_instantiation_must_be_global)
3506 << D;
3507 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
3508 return;
3509 }
3510
3511 // C++0x [temp.explicit]p2:
3512 // If the name declared in the explicit instantiation is an unqualified
3513 // name, the explicit instantiation shall appear in the namespace where
3514 // its template is declared or, if that namespace is inline (7.3.1), any
3515 // namespace from its enclosing namespace set.
3516 if (WasQualifiedName)
3517 return;
3518
3519 if (CurContext->Equals(ExpectedContext))
3520 return;
3521
3522 S.Diag(InstLoc, diag::err_explicit_instantiation_unqualified_wrong_namespace)
3523 << D << ExpectedContext;
3524 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
3525}
3526
3527/// \brief Determine whether the given scope specifier has a template-id in it.
3528static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
3529 if (!SS.isSet())
3530 return false;
3531
3532 // C++0x [temp.explicit]p2:
3533 // If the explicit instantiation is for a member function, a member class
3534 // or a static data member of a class template specialization, the name of
3535 // the class template specialization in the qualified-id for the member
3536 // name shall be a simple-template-id.
3537 //
3538 // C++98 has the same restriction, just worded differently.
3539 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
3540 NNS; NNS = NNS->getPrefix())
3541 if (Type *T = NNS->getAsType())
3542 if (isa<TemplateSpecializationType>(T))
3543 return true;
3544
3545 return false;
3546}
3547
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00003548// Explicit instantiation of a class template specialization
Douglas Gregor45f96552009-09-04 06:33:52 +00003549// FIXME: Implement extern template semantics
Douglas Gregor93dfdb12009-05-13 00:25:59 +00003550Sema::DeclResult
Mike Stump1eb44332009-09-09 15:08:12 +00003551Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor45f96552009-09-04 06:33:52 +00003552 SourceLocation ExternLoc,
3553 SourceLocation TemplateLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00003554 unsigned TagSpec,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00003555 SourceLocation KWLoc,
3556 const CXXScopeSpec &SS,
3557 TemplateTy TemplateD,
3558 SourceLocation TemplateNameLoc,
3559 SourceLocation LAngleLoc,
3560 ASTTemplateArgsPtr TemplateArgsIn,
3561 SourceLocation *TemplateArgLocs,
3562 SourceLocation RAngleLoc,
3563 AttributeList *Attr) {
3564 // Find the class template we're specializing
3565 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump1eb44332009-09-09 15:08:12 +00003566 ClassTemplateDecl *ClassTemplate
Douglas Gregor93dfdb12009-05-13 00:25:59 +00003567 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
3568
3569 // Check that the specialization uses the same tag kind as the
3570 // original template.
3571 TagDecl::TagKind Kind;
3572 switch (TagSpec) {
3573 default: assert(0 && "Unknown tag type!");
3574 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
3575 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
3576 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
3577 }
Douglas Gregor501c5ce2009-05-14 16:41:31 +00003578 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump1eb44332009-09-09 15:08:12 +00003579 Kind, KWLoc,
Douglas Gregor501c5ce2009-05-14 16:41:31 +00003580 *ClassTemplate->getIdentifier())) {
Mike Stump1eb44332009-09-09 15:08:12 +00003581 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor93dfdb12009-05-13 00:25:59 +00003582 << ClassTemplate
Mike Stump1eb44332009-09-09 15:08:12 +00003583 << CodeModificationHint::CreateReplacement(KWLoc,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00003584 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump1eb44332009-09-09 15:08:12 +00003585 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregor93dfdb12009-05-13 00:25:59 +00003586 diag::note_previous_use);
3587 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
3588 }
3589
Douglas Gregor558c0322009-10-14 23:41:34 +00003590 // C++0x [temp.explicit]p2:
3591 // There are two forms of explicit instantiation: an explicit instantiation
3592 // definition and an explicit instantiation declaration. An explicit
3593 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregord5cb8762009-10-07 00:13:32 +00003594 TemplateSpecializationKind TSK
3595 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
3596 : TSK_ExplicitInstantiationDeclaration;
3597
Douglas Gregor93dfdb12009-05-13 00:25:59 +00003598 // Translate the parser's template argument list in our AST format.
3599 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
3600 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
3601
3602 // Check that the template argument list is well-formed for this
3603 // template.
Anders Carlssonfb250522009-06-23 01:26:57 +00003604 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
3605 TemplateArgs.size());
Mike Stump1eb44332009-09-09 15:08:12 +00003606 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
Anders Carlsson9bff9a92009-06-05 02:12:32 +00003607 TemplateArgs.data(), TemplateArgs.size(),
Douglas Gregor16134c62009-07-01 00:28:38 +00003608 RAngleLoc, false, Converted))
Douglas Gregor93dfdb12009-05-13 00:25:59 +00003609 return true;
3610
Mike Stump1eb44332009-09-09 15:08:12 +00003611 assert((Converted.structuredSize() ==
Douglas Gregor93dfdb12009-05-13 00:25:59 +00003612 ClassTemplate->getTemplateParameters()->size()) &&
3613 "Converted template argument list is too short!");
Mike Stump1eb44332009-09-09 15:08:12 +00003614
Douglas Gregor93dfdb12009-05-13 00:25:59 +00003615 // Find the class template specialization declaration that
3616 // corresponds to these arguments.
3617 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00003618 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlssonfb250522009-06-23 01:26:57 +00003619 Converted.getFlatArguments(),
Douglas Gregor828e2262009-07-29 16:09:57 +00003620 Converted.flatSize(),
3621 Context);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00003622 void *InsertPos = 0;
3623 ClassTemplateSpecializationDecl *PrevDecl
3624 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
3625
Douglas Gregord5cb8762009-10-07 00:13:32 +00003626 // C++0x [temp.explicit]p2:
3627 // [...] An explicit instantiation shall appear in an enclosing
3628 // namespace of its template. [...]
3629 //
3630 // This is C++ DR 275.
Douglas Gregor558c0322009-10-14 23:41:34 +00003631 CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
3632 SS.isSet());
Douglas Gregord5cb8762009-10-07 00:13:32 +00003633
Douglas Gregor93dfdb12009-05-13 00:25:59 +00003634 ClassTemplateSpecializationDecl *Specialization = 0;
3635
3636 if (PrevDecl) {
Douglas Gregor89a5bea2009-10-15 22:53:21 +00003637 bool SuppressNew = false;
3638 if (CheckSpecializationInstantiationRedecl(*this, TemplateNameLoc, TSK,
3639 PrevDecl,
3640 PrevDecl->getSpecializationKind(),
3641 PrevDecl->getPointOfInstantiation(),
3642 SuppressNew))
Douglas Gregor93dfdb12009-05-13 00:25:59 +00003643 return DeclPtrTy::make(PrevDecl);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00003644
Douglas Gregor89a5bea2009-10-15 22:53:21 +00003645 if (SuppressNew)
Douglas Gregor52604ab2009-09-11 21:19:12 +00003646 return DeclPtrTy::make(PrevDecl);
Douglas Gregor89a5bea2009-10-15 22:53:21 +00003647
Douglas Gregor52604ab2009-09-11 21:19:12 +00003648 if (PrevDecl->getSpecializationKind() == TSK_ImplicitInstantiation ||
3649 PrevDecl->getSpecializationKind() == TSK_Undeclared) {
3650 // Since the only prior class template specialization with these
3651 // arguments was referenced but not declared, reuse that
3652 // declaration node as our own, updating its source location to
3653 // reflect our new declaration.
3654 Specialization = PrevDecl;
3655 Specialization->setLocation(TemplateNameLoc);
3656 PrevDecl = 0;
3657 }
Douglas Gregor89a5bea2009-10-15 22:53:21 +00003658 }
Douglas Gregor52604ab2009-09-11 21:19:12 +00003659
3660 if (!Specialization) {
Douglas Gregor93dfdb12009-05-13 00:25:59 +00003661 // Create a new class template specialization declaration node for
3662 // this explicit specialization.
3663 Specialization
Mike Stump1eb44332009-09-09 15:08:12 +00003664 = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00003665 ClassTemplate->getDeclContext(),
3666 TemplateNameLoc,
3667 ClassTemplate,
Douglas Gregor52604ab2009-09-11 21:19:12 +00003668 Converted, PrevDecl);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00003669
Douglas Gregor52604ab2009-09-11 21:19:12 +00003670 if (PrevDecl) {
3671 // Remove the previous declaration from the folding set, since we want
3672 // to introduce a new declaration.
3673 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
3674 ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
3675 }
3676
3677 // Insert the new specialization.
3678 ClassTemplate->getSpecializations().InsertNode(Specialization, InsertPos);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00003679 }
3680
3681 // Build the fully-sugared type for this explicit instantiation as
3682 // the user wrote in the explicit instantiation itself. This means
3683 // that we'll pretty-print the type retrieved from the
3684 // specialization's declaration the way that the user actually wrote
3685 // the explicit instantiation, rather than formatting the name based
3686 // on the "canonical" representation used to store the template
3687 // arguments in the specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00003688 QualType WrittenTy
3689 = Context.getTemplateSpecializationType(Name,
Anders Carlssonf4e2a2c2009-06-05 02:45:24 +00003690 TemplateArgs.data(),
Douglas Gregor93dfdb12009-05-13 00:25:59 +00003691 TemplateArgs.size(),
3692 Context.getTypeDeclType(Specialization));
3693 Specialization->setTypeAsWritten(WrittenTy);
3694 TemplateArgsIn.release();
3695
3696 // Add the explicit instantiation into its lexical context. However,
3697 // since explicit instantiations are never found by name lookup, we
3698 // just put it into the declaration context directly.
3699 Specialization->setLexicalDeclContext(CurContext);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003700 CurContext->addDecl(Specialization);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00003701
John McCall9cc78072009-09-11 07:25:08 +00003702 Specialization->setPointOfInstantiation(TemplateNameLoc);
3703
Douglas Gregor93dfdb12009-05-13 00:25:59 +00003704 // C++ [temp.explicit]p3:
Douglas Gregor93dfdb12009-05-13 00:25:59 +00003705 // A definition of a class template or class member template
3706 // shall be in scope at the point of the explicit instantiation of
3707 // the class template or class member template.
3708 //
3709 // This check comes when we actually try to perform the
3710 // instantiation.
Douglas Gregor89a5bea2009-10-15 22:53:21 +00003711 ClassTemplateSpecializationDecl *Def
3712 = cast_or_null<ClassTemplateSpecializationDecl>(
3713 Specialization->getDefinition(Context));
3714 if (!Def)
Douglas Gregord0e3daf2009-09-04 22:48:11 +00003715 InstantiateClassTemplateSpecialization(Specialization, TSK);
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00003716 else // Instantiate the members of this class template specialization.
Douglas Gregor89a5bea2009-10-15 22:53:21 +00003717 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00003718
3719 return DeclPtrTy::make(Specialization);
3720}
3721
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00003722// Explicit instantiation of a member class of a class template.
3723Sema::DeclResult
Mike Stump1eb44332009-09-09 15:08:12 +00003724Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor45f96552009-09-04 06:33:52 +00003725 SourceLocation ExternLoc,
3726 SourceLocation TemplateLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00003727 unsigned TagSpec,
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00003728 SourceLocation KWLoc,
3729 const CXXScopeSpec &SS,
3730 IdentifierInfo *Name,
3731 SourceLocation NameLoc,
3732 AttributeList *Attr) {
3733
Douglas Gregor402abb52009-05-28 23:31:59 +00003734 bool Owned = false;
John McCallc4e70192009-09-11 04:59:25 +00003735 bool IsDependent = false;
John McCall0f434ec2009-07-31 02:45:11 +00003736 DeclPtrTy TagD = ActOnTag(S, TagSpec, Action::TUK_Reference,
Douglas Gregor7cdbc582009-07-22 23:48:44 +00003737 KWLoc, SS, Name, NameLoc, Attr, AS_none,
John McCallc4e70192009-09-11 04:59:25 +00003738 MultiTemplateParamsArg(*this, 0, 0),
3739 Owned, IsDependent);
3740 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
3741
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00003742 if (!TagD)
3743 return true;
3744
3745 TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
3746 if (Tag->isEnum()) {
3747 Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
3748 << Context.getTypeDeclType(Tag);
3749 return true;
3750 }
3751
Douglas Gregord0c87372009-05-27 17:30:49 +00003752 if (Tag->isInvalidDecl())
3753 return true;
Douglas Gregor558c0322009-10-14 23:41:34 +00003754
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00003755 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
3756 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
3757 if (!Pattern) {
3758 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
3759 << Context.getTypeDeclType(Record);
3760 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
3761 return true;
3762 }
3763
Douglas Gregor558c0322009-10-14 23:41:34 +00003764 // C++0x [temp.explicit]p2:
3765 // If the explicit instantiation is for a class or member class, the
3766 // elaborated-type-specifier in the declaration shall include a
3767 // simple-template-id.
3768 //
3769 // C++98 has the same restriction, just worded differently.
3770 if (!ScopeSpecifierHasTemplateId(SS))
3771 Diag(TemplateLoc, diag::err_explicit_instantiation_without_qualified_id)
3772 << Record << SS.getRange();
3773
3774 // C++0x [temp.explicit]p2:
3775 // There are two forms of explicit instantiation: an explicit instantiation
3776 // definition and an explicit instantiation declaration. An explicit
3777 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregora74bbe22009-10-14 21:46:58 +00003778 TemplateSpecializationKind TSK
3779 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
3780 : TSK_ExplicitInstantiationDeclaration;
3781
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00003782 // C++0x [temp.explicit]p2:
3783 // [...] An explicit instantiation shall appear in an enclosing
3784 // namespace of its template. [...]
3785 //
3786 // This is C++ DR 275.
Douglas Gregor558c0322009-10-14 23:41:34 +00003787 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
Douglas Gregor454885e2009-10-15 15:54:05 +00003788
3789 // Verify that it is okay to explicitly instantiate here.
Douglas Gregor583f33b2009-10-15 18:07:02 +00003790 CXXRecordDecl *PrevDecl
3791 = cast_or_null<CXXRecordDecl>(Record->getPreviousDeclaration());
3792 if (!PrevDecl && Record->getDefinition(Context))
3793 PrevDecl = Record;
3794 if (PrevDecl) {
Douglas Gregor454885e2009-10-15 15:54:05 +00003795 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
3796 bool SuppressNew = false;
3797 assert(MSInfo && "No member specialization information?");
3798 if (CheckSpecializationInstantiationRedecl(*this, TemplateLoc, TSK,
3799 PrevDecl,
3800 MSInfo->getTemplateSpecializationKind(),
3801 MSInfo->getPointOfInstantiation(),
3802 SuppressNew))
3803 return true;
3804 if (SuppressNew)
3805 return TagD;
3806 }
3807
Douglas Gregor89a5bea2009-10-15 22:53:21 +00003808 CXXRecordDecl *RecordDef
3809 = cast_or_null<CXXRecordDecl>(Record->getDefinition(Context));
3810 if (!RecordDef) {
Douglas Gregorbf7643e2009-10-15 12:53:22 +00003811 // C++ [temp.explicit]p3:
3812 // A definition of a member class of a class template shall be in scope
3813 // at the point of an explicit instantiation of the member class.
3814 CXXRecordDecl *Def
3815 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition(Context));
3816 if (!Def) {
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00003817 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
3818 << 0 << Record->getDeclName() << Record->getDeclContext();
Douglas Gregorbf7643e2009-10-15 12:53:22 +00003819 Diag(Pattern->getLocation(), diag::note_forward_declaration)
3820 << Pattern;
3821 return true;
Douglas Gregor89a5bea2009-10-15 22:53:21 +00003822 } else if (InstantiateClass(NameLoc, Record, Def,
Douglas Gregorbf7643e2009-10-15 12:53:22 +00003823 getTemplateInstantiationArgs(Record),
3824 TSK))
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00003825 return true;
John McCallce3ff2b2009-08-25 22:02:44 +00003826 } else // Instantiate all of the members of the class.
Douglas Gregor89a5bea2009-10-15 22:53:21 +00003827 InstantiateClassMembers(NameLoc, RecordDef,
Douglas Gregord0e3daf2009-09-04 22:48:11 +00003828 getTemplateInstantiationArgs(Record), TSK);
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00003829
Mike Stump390b4cc2009-05-16 07:39:55 +00003830 // FIXME: We don't have any representation for explicit instantiations of
3831 // member classes. Such a representation is not needed for compilation, but it
3832 // should be available for clients that want to see all of the declarations in
3833 // the source code.
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00003834 return TagD;
3835}
3836
Douglas Gregord5a423b2009-09-25 18:43:00 +00003837Sema::DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
3838 SourceLocation ExternLoc,
3839 SourceLocation TemplateLoc,
3840 Declarator &D) {
3841 // Explicit instantiations always require a name.
3842 DeclarationName Name = GetNameForDeclarator(D);
3843 if (!Name) {
3844 if (!D.isInvalidType())
3845 Diag(D.getDeclSpec().getSourceRange().getBegin(),
3846 diag::err_explicit_instantiation_requires_name)
3847 << D.getDeclSpec().getSourceRange()
3848 << D.getSourceRange();
3849
3850 return true;
3851 }
3852
3853 // The scope passed in may not be a decl scope. Zip up the scope tree until
3854 // we find one that is.
3855 while ((S->getFlags() & Scope::DeclScope) == 0 ||
3856 (S->getFlags() & Scope::TemplateParamScope) != 0)
3857 S = S->getParent();
3858
3859 // Determine the type of the declaration.
3860 QualType R = GetTypeForDeclarator(D, S, 0);
3861 if (R.isNull())
3862 return true;
3863
3864 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
3865 // Cannot explicitly instantiate a typedef.
3866 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
3867 << Name;
3868 return true;
3869 }
3870
Douglas Gregor663b5a02009-10-14 20:14:33 +00003871 // C++0x [temp.explicit]p1:
3872 // [...] An explicit instantiation of a function template shall not use the
3873 // inline or constexpr specifiers.
3874 // Presumably, this also applies to member functions of class templates as
3875 // well.
3876 if (D.getDeclSpec().isInlineSpecified() && getLangOptions().CPlusPlus0x)
3877 Diag(D.getDeclSpec().getInlineSpecLoc(),
3878 diag::err_explicit_instantiation_inline)
3879 << CodeModificationHint::CreateRemoval(
3880 SourceRange(D.getDeclSpec().getInlineSpecLoc()));
3881
3882 // FIXME: check for constexpr specifier.
3883
Douglas Gregor558c0322009-10-14 23:41:34 +00003884 // C++0x [temp.explicit]p2:
3885 // There are two forms of explicit instantiation: an explicit instantiation
3886 // definition and an explicit instantiation declaration. An explicit
3887 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregord5a423b2009-09-25 18:43:00 +00003888 TemplateSpecializationKind TSK
3889 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
3890 : TSK_ExplicitInstantiationDeclaration;
Douglas Gregor558c0322009-10-14 23:41:34 +00003891
John McCallf36e02d2009-10-09 21:13:30 +00003892 LookupResult Previous;
3893 LookupParsedName(Previous, S, &D.getCXXScopeSpec(),
3894 Name, LookupOrdinaryName);
Douglas Gregord5a423b2009-09-25 18:43:00 +00003895
3896 if (!R->isFunctionType()) {
3897 // C++ [temp.explicit]p1:
3898 // A [...] static data member of a class template can be explicitly
3899 // instantiated from the member definition associated with its class
3900 // template.
3901 if (Previous.isAmbiguous()) {
3902 return DiagnoseAmbiguousLookup(Previous, Name, D.getIdentifierLoc(),
3903 D.getSourceRange());
3904 }
3905
John McCallf36e02d2009-10-09 21:13:30 +00003906 VarDecl *Prev = dyn_cast_or_null<VarDecl>(
3907 Previous.getAsSingleDecl(Context));
Douglas Gregord5a423b2009-09-25 18:43:00 +00003908 if (!Prev || !Prev->isStaticDataMember()) {
3909 // We expect to see a data data member here.
3910 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
3911 << Name;
3912 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
3913 P != PEnd; ++P)
John McCallf36e02d2009-10-09 21:13:30 +00003914 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregord5a423b2009-09-25 18:43:00 +00003915 return true;
3916 }
3917
3918 if (!Prev->getInstantiatedFromStaticDataMember()) {
3919 // FIXME: Check for explicit specialization?
3920 Diag(D.getIdentifierLoc(),
3921 diag::err_explicit_instantiation_data_member_not_instantiated)
3922 << Prev;
3923 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
3924 // FIXME: Can we provide a note showing where this was declared?
3925 return true;
3926 }
3927
Douglas Gregor558c0322009-10-14 23:41:34 +00003928 // C++0x [temp.explicit]p2:
3929 // If the explicit instantiation is for a member function, a member class
3930 // or a static data member of a class template specialization, the name of
3931 // the class template specialization in the qualified-id for the member
3932 // name shall be a simple-template-id.
3933 //
3934 // C++98 has the same restriction, just worded differently.
3935 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
3936 Diag(D.getIdentifierLoc(),
3937 diag::err_explicit_instantiation_without_qualified_id)
3938 << Prev << D.getCXXScopeSpec().getRange();
3939
3940 // Check the scope of this explicit instantiation.
3941 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
3942
Douglas Gregor454885e2009-10-15 15:54:05 +00003943 // Verify that it is okay to explicitly instantiate here.
3944 MemberSpecializationInfo *MSInfo = Prev->getMemberSpecializationInfo();
3945 assert(MSInfo && "Missing static data member specialization info?");
3946 bool SuppressNew = false;
3947 if (CheckSpecializationInstantiationRedecl(*this, D.getIdentifierLoc(), TSK,
3948 Prev,
3949 MSInfo->getTemplateSpecializationKind(),
3950 MSInfo->getPointOfInstantiation(),
3951 SuppressNew))
3952 return true;
3953 if (SuppressNew)
3954 return DeclPtrTy();
3955
Douglas Gregord5a423b2009-09-25 18:43:00 +00003956 // Instantiate static data member.
Douglas Gregor0a897e32009-10-15 17:21:20 +00003957 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregord5a423b2009-09-25 18:43:00 +00003958 if (TSK == TSK_ExplicitInstantiationDefinition)
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00003959 InstantiateStaticDataMemberDefinition(D.getIdentifierLoc(), Prev, false,
3960 /*DefinitionRequired=*/true);
Douglas Gregord5a423b2009-09-25 18:43:00 +00003961
3962 // FIXME: Create an ExplicitInstantiation node?
3963 return DeclPtrTy();
3964 }
3965
Douglas Gregor0b60d9e2009-09-25 23:53:26 +00003966 // If the declarator is a template-id, translate the parser's template
3967 // argument list into our AST format.
Douglas Gregordb422df2009-09-25 21:45:23 +00003968 bool HasExplicitTemplateArgs = false;
3969 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
3970 if (D.getKind() == Declarator::DK_TemplateId) {
3971 TemplateIdAnnotation *TemplateId = D.getTemplateId();
3972 ASTTemplateArgsPtr TemplateArgsPtr(*this,
3973 TemplateId->getTemplateArgs(),
3974 TemplateId->getTemplateArgIsType(),
3975 TemplateId->NumArgs);
3976 translateTemplateArguments(TemplateArgsPtr,
3977 TemplateId->getTemplateArgLocations(),
3978 TemplateArgs);
3979 HasExplicitTemplateArgs = true;
Douglas Gregorb2f81cf2009-10-01 23:51:25 +00003980 TemplateArgsPtr.release();
Douglas Gregordb422df2009-09-25 21:45:23 +00003981 }
Douglas Gregor0b60d9e2009-09-25 23:53:26 +00003982
Douglas Gregord5a423b2009-09-25 18:43:00 +00003983 // C++ [temp.explicit]p1:
3984 // A [...] function [...] can be explicitly instantiated from its template.
3985 // A member function [...] of a class template can be explicitly
3986 // instantiated from the member definition associated with its class
3987 // template.
Douglas Gregord5a423b2009-09-25 18:43:00 +00003988 llvm::SmallVector<FunctionDecl *, 8> Matches;
3989 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
3990 P != PEnd; ++P) {
3991 NamedDecl *Prev = *P;
Douglas Gregordb422df2009-09-25 21:45:23 +00003992 if (!HasExplicitTemplateArgs) {
3993 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
3994 if (Context.hasSameUnqualifiedType(Method->getType(), R)) {
3995 Matches.clear();
3996 Matches.push_back(Method);
3997 break;
3998 }
Douglas Gregord5a423b2009-09-25 18:43:00 +00003999 }
4000 }
4001
4002 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
4003 if (!FunTmpl)
4004 continue;
4005
4006 TemplateDeductionInfo Info(Context);
4007 FunctionDecl *Specialization = 0;
4008 if (TemplateDeductionResult TDK
Douglas Gregordb422df2009-09-25 21:45:23 +00004009 = DeduceTemplateArguments(FunTmpl, HasExplicitTemplateArgs,
4010 TemplateArgs.data(), TemplateArgs.size(),
Douglas Gregord5a423b2009-09-25 18:43:00 +00004011 R, Specialization, Info)) {
4012 // FIXME: Keep track of almost-matches?
4013 (void)TDK;
4014 continue;
4015 }
4016
4017 Matches.push_back(Specialization);
4018 }
4019
4020 // Find the most specialized function template specialization.
4021 FunctionDecl *Specialization
4022 = getMostSpecialized(Matches.data(), Matches.size(), TPOC_Other,
4023 D.getIdentifierLoc(),
4024 PartialDiagnostic(diag::err_explicit_instantiation_not_known) << Name,
4025 PartialDiagnostic(diag::err_explicit_instantiation_ambiguous) << Name,
4026 PartialDiagnostic(diag::note_explicit_instantiation_candidate));
4027
4028 if (!Specialization)
4029 return true;
4030
Douglas Gregor0a897e32009-10-15 17:21:20 +00004031 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
Douglas Gregord5a423b2009-09-25 18:43:00 +00004032 Diag(D.getIdentifierLoc(),
4033 diag::err_explicit_instantiation_member_function_not_instantiated)
4034 << Specialization
4035 << (Specialization->getTemplateSpecializationKind() ==
4036 TSK_ExplicitSpecialization);
4037 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
4038 return true;
Douglas Gregor0a897e32009-10-15 17:21:20 +00004039 }
Douglas Gregor558c0322009-10-14 23:41:34 +00004040
Douglas Gregor0a897e32009-10-15 17:21:20 +00004041 FunctionDecl *PrevDecl = Specialization->getPreviousDeclaration();
Douglas Gregor583f33b2009-10-15 18:07:02 +00004042 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
4043 PrevDecl = Specialization;
4044
Douglas Gregor0a897e32009-10-15 17:21:20 +00004045 if (PrevDecl) {
4046 bool SuppressNew = false;
4047 if (CheckSpecializationInstantiationRedecl(*this, D.getIdentifierLoc(), TSK,
4048 PrevDecl,
4049 PrevDecl->getTemplateSpecializationKind(),
4050 PrevDecl->getPointOfInstantiation(),
4051 SuppressNew))
4052 return true;
4053
4054 // FIXME: We may still want to build some representation of this
4055 // explicit specialization.
4056 if (SuppressNew)
4057 return DeclPtrTy();
4058 }
4059
4060 if (TSK == TSK_ExplicitInstantiationDefinition)
4061 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization,
4062 false, /*DefinitionRequired=*/true);
4063
4064 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
4065
Douglas Gregor558c0322009-10-14 23:41:34 +00004066 // C++0x [temp.explicit]p2:
4067 // If the explicit instantiation is for a member function, a member class
4068 // or a static data member of a class template specialization, the name of
4069 // the class template specialization in the qualified-id for the member
4070 // name shall be a simple-template-id.
4071 //
4072 // C++98 has the same restriction, just worded differently.
Douglas Gregor0a897e32009-10-15 17:21:20 +00004073 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
Douglas Gregor558c0322009-10-14 23:41:34 +00004074 if (D.getKind() != Declarator::DK_TemplateId && !FunTmpl &&
4075 D.getCXXScopeSpec().isSet() &&
4076 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
4077 Diag(D.getIdentifierLoc(),
4078 diag::err_explicit_instantiation_without_qualified_id)
4079 << Specialization << D.getCXXScopeSpec().getRange();
4080
4081 CheckExplicitInstantiationScope(*this,
4082 FunTmpl? (NamedDecl *)FunTmpl
4083 : Specialization->getInstantiatedFromMemberFunction(),
4084 D.getIdentifierLoc(),
4085 D.getCXXScopeSpec().isSet());
4086
Douglas Gregord5a423b2009-09-25 18:43:00 +00004087 // FIXME: Create some kind of ExplicitInstantiationDecl here.
4088 return DeclPtrTy();
4089}
4090
Douglas Gregord57959a2009-03-27 23:10:48 +00004091Sema::TypeResult
John McCallc4e70192009-09-11 04:59:25 +00004092Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
4093 const CXXScopeSpec &SS, IdentifierInfo *Name,
4094 SourceLocation TagLoc, SourceLocation NameLoc) {
4095 // This has to hold, because SS is expected to be defined.
4096 assert(Name && "Expected a name in a dependent tag");
4097
4098 NestedNameSpecifier *NNS
4099 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
4100 if (!NNS)
4101 return true;
4102
4103 QualType T = CheckTypenameType(NNS, *Name, SourceRange(TagLoc, NameLoc));
4104 if (T.isNull())
4105 return true;
4106
4107 TagDecl::TagKind TagKind = TagDecl::getTagKindForTypeSpec(TagSpec);
4108 QualType ElabType = Context.getElaboratedType(T, TagKind);
4109
4110 return ElabType.getAsOpaquePtr();
4111}
4112
4113Sema::TypeResult
Douglas Gregord57959a2009-03-27 23:10:48 +00004114Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
4115 const IdentifierInfo &II, SourceLocation IdLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +00004116 NestedNameSpecifier *NNS
Douglas Gregord57959a2009-03-27 23:10:48 +00004117 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
4118 if (!NNS)
4119 return true;
4120
4121 QualType T = CheckTypenameType(NNS, II, SourceRange(TypenameLoc, IdLoc));
Douglas Gregor31a19b62009-04-01 21:51:26 +00004122 if (T.isNull())
4123 return true;
Douglas Gregord57959a2009-03-27 23:10:48 +00004124 return T.getAsOpaquePtr();
4125}
4126
Douglas Gregor17343172009-04-01 00:28:59 +00004127Sema::TypeResult
4128Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
4129 SourceLocation TemplateLoc, TypeTy *Ty) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00004130 QualType T = GetTypeFromParser(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00004131 NestedNameSpecifier *NNS
Douglas Gregor17343172009-04-01 00:28:59 +00004132 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Mike Stump1eb44332009-09-09 15:08:12 +00004133 const TemplateSpecializationType *TemplateId
John McCall183700f2009-09-21 23:43:11 +00004134 = T->getAs<TemplateSpecializationType>();
Douglas Gregor17343172009-04-01 00:28:59 +00004135 assert(TemplateId && "Expected a template specialization type");
4136
Douglas Gregor6946baf2009-09-02 13:05:45 +00004137 if (computeDeclContext(SS, false)) {
4138 // If we can compute a declaration context, then the "typename"
4139 // keyword was superfluous. Just build a QualifiedNameType to keep
4140 // track of the nested-name-specifier.
Mike Stump1eb44332009-09-09 15:08:12 +00004141
Douglas Gregor6946baf2009-09-02 13:05:45 +00004142 // FIXME: Note that the QualifiedNameType had the "typename" keyword!
4143 return Context.getQualifiedNameType(NNS, T).getAsOpaquePtr();
4144 }
Mike Stump1eb44332009-09-09 15:08:12 +00004145
Douglas Gregor6946baf2009-09-02 13:05:45 +00004146 return Context.getTypenameType(NNS, TemplateId).getAsOpaquePtr();
Douglas Gregor17343172009-04-01 00:28:59 +00004147}
4148
Douglas Gregord57959a2009-03-27 23:10:48 +00004149/// \brief Build the type that describes a C++ typename specifier,
4150/// e.g., "typename T::type".
4151QualType
4152Sema::CheckTypenameType(NestedNameSpecifier *NNS, const IdentifierInfo &II,
4153 SourceRange Range) {
Douglas Gregor42af25f2009-05-11 19:58:34 +00004154 CXXRecordDecl *CurrentInstantiation = 0;
4155 if (NNS->isDependent()) {
4156 CurrentInstantiation = getCurrentInstantiationOf(NNS);
Douglas Gregord57959a2009-03-27 23:10:48 +00004157
Douglas Gregor42af25f2009-05-11 19:58:34 +00004158 // If the nested-name-specifier does not refer to the current
4159 // instantiation, then build a typename type.
4160 if (!CurrentInstantiation)
4161 return Context.getTypenameType(NNS, &II);
Mike Stump1eb44332009-09-09 15:08:12 +00004162
Douglas Gregorde18d122009-09-02 13:12:51 +00004163 // The nested-name-specifier refers to the current instantiation, so the
4164 // "typename" keyword itself is superfluous. In C++03, the program is
Mike Stump1eb44332009-09-09 15:08:12 +00004165 // actually ill-formed. However, DR 382 (in C++0x CD1) allows such
Douglas Gregorde18d122009-09-02 13:12:51 +00004166 // extraneous "typename" keywords, and we retroactively apply this DR to
4167 // C++03 code.
Douglas Gregor42af25f2009-05-11 19:58:34 +00004168 }
Douglas Gregord57959a2009-03-27 23:10:48 +00004169
Douglas Gregor42af25f2009-05-11 19:58:34 +00004170 DeclContext *Ctx = 0;
4171
4172 if (CurrentInstantiation)
4173 Ctx = CurrentInstantiation;
4174 else {
4175 CXXScopeSpec SS;
4176 SS.setScopeRep(NNS);
4177 SS.setRange(Range);
4178 if (RequireCompleteDeclContext(SS))
4179 return QualType();
4180
4181 Ctx = computeDeclContext(SS);
4182 }
Douglas Gregord57959a2009-03-27 23:10:48 +00004183 assert(Ctx && "No declaration context?");
4184
4185 DeclarationName Name(&II);
John McCallf36e02d2009-10-09 21:13:30 +00004186 LookupResult Result;
4187 LookupQualifiedName(Result, Ctx, Name, LookupOrdinaryName, false);
Douglas Gregord57959a2009-03-27 23:10:48 +00004188 unsigned DiagID = 0;
4189 Decl *Referenced = 0;
4190 switch (Result.getKind()) {
4191 case LookupResult::NotFound:
Douglas Gregor3f093272009-10-13 21:16:44 +00004192 DiagID = diag::err_typename_nested_not_found;
Douglas Gregord57959a2009-03-27 23:10:48 +00004193 break;
4194
4195 case LookupResult::Found:
John McCallf36e02d2009-10-09 21:13:30 +00004196 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
Douglas Gregord57959a2009-03-27 23:10:48 +00004197 // We found a type. Build a QualifiedNameType, since the
4198 // typename-specifier was just sugar. FIXME: Tell
4199 // QualifiedNameType that it has a "typename" prefix.
4200 return Context.getQualifiedNameType(NNS, Context.getTypeDeclType(Type));
4201 }
4202
4203 DiagID = diag::err_typename_nested_not_type;
John McCallf36e02d2009-10-09 21:13:30 +00004204 Referenced = Result.getFoundDecl();
Douglas Gregord57959a2009-03-27 23:10:48 +00004205 break;
4206
4207 case LookupResult::FoundOverloaded:
4208 DiagID = diag::err_typename_nested_not_type;
4209 Referenced = *Result.begin();
4210 break;
4211
John McCall6e247262009-10-10 05:48:19 +00004212 case LookupResult::Ambiguous:
Douglas Gregord57959a2009-03-27 23:10:48 +00004213 DiagnoseAmbiguousLookup(Result, Name, Range.getEnd(), Range);
4214 return QualType();
4215 }
4216
4217 // If we get here, it's because name lookup did not find a
4218 // type. Emit an appropriate diagnostic and return an error.
Douglas Gregor3f093272009-10-13 21:16:44 +00004219 Diag(Range.getEnd(), DiagID) << Range << Name << Ctx;
Douglas Gregord57959a2009-03-27 23:10:48 +00004220 if (Referenced)
4221 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
4222 << Name;
4223 return QualType();
4224}
Douglas Gregor4a959d82009-08-06 16:20:37 +00004225
4226namespace {
4227 // See Sema::RebuildTypeInCurrentInstantiation
Mike Stump1eb44332009-09-09 15:08:12 +00004228 class VISIBILITY_HIDDEN CurrentInstantiationRebuilder
4229 : public TreeTransform<CurrentInstantiationRebuilder> {
Douglas Gregor4a959d82009-08-06 16:20:37 +00004230 SourceLocation Loc;
4231 DeclarationName Entity;
Mike Stump1eb44332009-09-09 15:08:12 +00004232
Douglas Gregor4a959d82009-08-06 16:20:37 +00004233 public:
Mike Stump1eb44332009-09-09 15:08:12 +00004234 CurrentInstantiationRebuilder(Sema &SemaRef,
Douglas Gregor4a959d82009-08-06 16:20:37 +00004235 SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +00004236 DeclarationName Entity)
4237 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
Douglas Gregor4a959d82009-08-06 16:20:37 +00004238 Loc(Loc), Entity(Entity) { }
Mike Stump1eb44332009-09-09 15:08:12 +00004239
4240 /// \brief Determine whether the given type \p T has already been
Douglas Gregor4a959d82009-08-06 16:20:37 +00004241 /// transformed.
4242 ///
4243 /// For the purposes of type reconstruction, a type has already been
4244 /// transformed if it is NULL or if it is not dependent.
4245 bool AlreadyTransformed(QualType T) {
4246 return T.isNull() || !T->isDependentType();
4247 }
Mike Stump1eb44332009-09-09 15:08:12 +00004248
4249 /// \brief Returns the location of the entity whose type is being
Douglas Gregor4a959d82009-08-06 16:20:37 +00004250 /// rebuilt.
4251 SourceLocation getBaseLocation() { return Loc; }
Mike Stump1eb44332009-09-09 15:08:12 +00004252
Douglas Gregor4a959d82009-08-06 16:20:37 +00004253 /// \brief Returns the name of the entity whose type is being rebuilt.
4254 DeclarationName getBaseEntity() { return Entity; }
Mike Stump1eb44332009-09-09 15:08:12 +00004255
Douglas Gregor4a959d82009-08-06 16:20:37 +00004256 /// \brief Transforms an expression by returning the expression itself
4257 /// (an identity function).
4258 ///
4259 /// FIXME: This is completely unsafe; we will need to actually clone the
4260 /// expressions.
4261 Sema::OwningExprResult TransformExpr(Expr *E) {
4262 return getSema().Owned(E);
4263 }
Mike Stump1eb44332009-09-09 15:08:12 +00004264
Douglas Gregor4a959d82009-08-06 16:20:37 +00004265 /// \brief Transforms a typename type by determining whether the type now
4266 /// refers to a member of the current instantiation, and then
4267 /// type-checking and building a QualifiedNameType (when possible).
John McCalla2becad2009-10-21 00:40:46 +00004268 QualType TransformTypenameType(TypeLocBuilder &TLB, TypenameTypeLoc TL);
4269 QualType TransformTypenameType(TypenameType *T);
Douglas Gregor4a959d82009-08-06 16:20:37 +00004270 };
4271}
4272
Mike Stump1eb44332009-09-09 15:08:12 +00004273QualType
John McCalla2becad2009-10-21 00:40:46 +00004274CurrentInstantiationRebuilder::TransformTypenameType(TypeLocBuilder &TLB,
4275 TypenameTypeLoc TL) {
4276 QualType Result = TransformTypenameType(TL.getTypePtr());
4277 if (Result.isNull())
4278 return QualType();
4279
4280 TypenameTypeLoc NewTL = TLB.push<TypenameTypeLoc>(Result);
4281 NewTL.setNameLoc(TL.getNameLoc());
4282
4283 return Result;
4284}
4285
4286QualType
4287CurrentInstantiationRebuilder::TransformTypenameType(TypenameType *T) {
4288
Douglas Gregor4a959d82009-08-06 16:20:37 +00004289 NestedNameSpecifier *NNS
4290 = TransformNestedNameSpecifier(T->getQualifier(),
4291 /*FIXME:*/SourceRange(getBaseLocation()));
4292 if (!NNS)
4293 return QualType();
4294
4295 // If the nested-name-specifier did not change, and we cannot compute the
4296 // context corresponding to the nested-name-specifier, then this
4297 // typename type will not change; exit early.
4298 CXXScopeSpec SS;
4299 SS.setRange(SourceRange(getBaseLocation()));
4300 SS.setScopeRep(NNS);
4301 if (NNS == T->getQualifier() && getSema().computeDeclContext(SS) == 0)
4302 return QualType(T, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00004303
4304 // Rebuild the typename type, which will probably turn into a
Douglas Gregor4a959d82009-08-06 16:20:37 +00004305 // QualifiedNameType.
4306 if (const TemplateSpecializationType *TemplateId = T->getTemplateId()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004307 QualType NewTemplateId
Douglas Gregor4a959d82009-08-06 16:20:37 +00004308 = TransformType(QualType(TemplateId, 0));
4309 if (NewTemplateId.isNull())
4310 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00004311
Douglas Gregor4a959d82009-08-06 16:20:37 +00004312 if (NNS == T->getQualifier() &&
4313 NewTemplateId == QualType(TemplateId, 0))
4314 return QualType(T, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00004315
Douglas Gregor4a959d82009-08-06 16:20:37 +00004316 return getDerived().RebuildTypenameType(NNS, NewTemplateId);
4317 }
Mike Stump1eb44332009-09-09 15:08:12 +00004318
Douglas Gregor4a959d82009-08-06 16:20:37 +00004319 return getDerived().RebuildTypenameType(NNS, T->getIdentifier());
4320}
4321
4322/// \brief Rebuilds a type within the context of the current instantiation.
4323///
Mike Stump1eb44332009-09-09 15:08:12 +00004324/// The type \p T is part of the type of an out-of-line member definition of
Douglas Gregor4a959d82009-08-06 16:20:37 +00004325/// a class template (or class template partial specialization) that was parsed
Mike Stump1eb44332009-09-09 15:08:12 +00004326/// and constructed before we entered the scope of the class template (or
Douglas Gregor4a959d82009-08-06 16:20:37 +00004327/// partial specialization thereof). This routine will rebuild that type now
4328/// that we have entered the declarator's scope, which may produce different
4329/// canonical types, e.g.,
4330///
4331/// \code
4332/// template<typename T>
4333/// struct X {
4334/// typedef T* pointer;
4335/// pointer data();
4336/// };
4337///
4338/// template<typename T>
4339/// typename X<T>::pointer X<T>::data() { ... }
4340/// \endcode
4341///
4342/// Here, the type "typename X<T>::pointer" will be created as a TypenameType,
4343/// since we do not know that we can look into X<T> when we parsed the type.
4344/// This function will rebuild the type, performing the lookup of "pointer"
4345/// in X<T> and returning a QualifiedNameType whose canonical type is the same
4346/// as the canonical type of T*, allowing the return types of the out-of-line
4347/// definition and the declaration to match.
4348QualType Sema::RebuildTypeInCurrentInstantiation(QualType T, SourceLocation Loc,
4349 DeclarationName Name) {
4350 if (T.isNull() || !T->isDependentType())
4351 return T;
Mike Stump1eb44332009-09-09 15:08:12 +00004352
Douglas Gregor4a959d82009-08-06 16:20:37 +00004353 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
4354 return Rebuilder.TransformType(T);
Benjamin Kramer27ba2f02009-08-11 22:33:06 +00004355}
Douglas Gregorbf4ea562009-09-15 16:23:51 +00004356
4357/// \brief Produces a formatted string that describes the binding of
4358/// template parameters to template arguments.
4359std::string
4360Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
4361 const TemplateArgumentList &Args) {
4362 std::string Result;
4363
4364 if (!Params || Params->size() == 0)
4365 return Result;
4366
4367 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
4368 if (I == 0)
4369 Result += "[with ";
4370 else
4371 Result += ", ";
4372
4373 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
4374 Result += Id->getName();
4375 } else {
4376 Result += '$';
4377 Result += llvm::utostr(I);
4378 }
4379
4380 Result += " = ";
4381
4382 switch (Args[I].getKind()) {
4383 case TemplateArgument::Null:
4384 Result += "<no value>";
4385 break;
4386
4387 case TemplateArgument::Type: {
4388 std::string TypeStr;
4389 Args[I].getAsType().getAsStringInternal(TypeStr,
4390 Context.PrintingPolicy);
4391 Result += TypeStr;
4392 break;
4393 }
4394
4395 case TemplateArgument::Declaration: {
4396 bool Unnamed = true;
4397 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(Args[I].getAsDecl())) {
4398 if (ND->getDeclName()) {
4399 Unnamed = false;
4400 Result += ND->getNameAsString();
4401 }
4402 }
4403
4404 if (Unnamed) {
4405 Result += "<anonymous>";
4406 }
4407 break;
4408 }
4409
4410 case TemplateArgument::Integral: {
4411 Result += Args[I].getAsIntegral()->toString(10);
4412 break;
4413 }
4414
4415 case TemplateArgument::Expression: {
4416 assert(false && "No expressions in deduced template arguments!");
4417 Result += "<expression>";
4418 break;
4419 }
4420
4421 case TemplateArgument::Pack:
4422 // FIXME: Format template argument packs
4423 Result += "<template argument pack>";
4424 break;
4425 }
4426 }
4427
4428 Result += ']';
4429 return Result;
4430}