blob: 8a12ac11684d85e7d883ec1dfab955ff426979fe [file] [log] [blame]
Douglas Gregor5101c242008-12-05 18:15:24 +00001//===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===/
Douglas Gregor5101c242008-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 Gregorfe1e1102009-02-27 19:31:52 +00007//===----------------------------------------------------------------------===/
Douglas Gregor5101c242008-12-05 18:15:24 +00008//
9// This file implements semantic analysis for C++ templates.
Douglas Gregorfe1e1102009-02-27 19:31:52 +000010//===----------------------------------------------------------------------===/
Douglas Gregor5101c242008-12-05 18:15:24 +000011
12#include "Sema.h"
Douglas Gregor15acfb92009-08-06 16:20:37 +000013#include "TreeTransform.h"
Douglas Gregorcd72ba92009-02-06 22:42:48 +000014#include "clang/AST/ASTContext.h"
Douglas Gregor4619e432008-12-05 23:32:09 +000015#include "clang/AST/Expr.h"
Douglas Gregorccb07762009-02-11 19:52:55 +000016#include "clang/AST/ExprCXX.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000017#include "clang/AST/DeclTemplate.h"
Douglas Gregor5101c242008-12-05 18:15:24 +000018#include "clang/Parse/DeclSpec.h"
19#include "clang/Basic/LangOptions.h"
Douglas Gregor450f00842009-09-25 18:43:00 +000020#include "clang/Basic/PartialDiagnostic.h"
Douglas Gregor15acfb92009-08-06 16:20:37 +000021#include "llvm/Support/Compiler.h"
Douglas Gregorbe999392009-09-15 16:23:51 +000022#include "llvm/ADT/StringExtras.h"
Douglas Gregor5101c242008-12-05 18:15:24 +000023using namespace clang;
24
Douglas Gregorb7bfe792009-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 Stump11289f42009-09-09 15:08:12 +000031
Douglas Gregorb7bfe792009-09-02 22:59:36 +000032 if (isa<TemplateDecl>(D))
33 return D;
Mike Stump11289f42009-09-09 15:08:12 +000034
Douglas Gregorb7bfe792009-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()) {
48 Record = cast<CXXRecordDecl>(Record->getCanonicalDecl());
49 if (Record->getDescribedClassTemplate())
50 return Record->getDescribedClassTemplate();
51
52 if (ClassTemplateSpecializationDecl *Spec
53 = dyn_cast<ClassTemplateSpecializationDecl>(Record))
54 return Spec->getSpecializedTemplate();
55 }
Mike Stump11289f42009-09-09 15:08:12 +000056
Douglas Gregorb7bfe792009-09-02 22:59:36 +000057 return 0;
58 }
Mike Stump11289f42009-09-09 15:08:12 +000059
Douglas Gregorb7bfe792009-09-02 22:59:36 +000060 OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D);
61 if (!Ovl)
62 return 0;
Mike Stump11289f42009-09-09 15:08:12 +000063
Douglas Gregorb7bfe792009-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 Stump11289f42009-09-09 15:08:12 +000075
Douglas Gregorb7bfe792009-09-02 22:59:36 +000076 if (F != FEnd) {
77 // Build an overloaded function decl containing only the
78 // function templates in Ovl.
Mike Stump11289f42009-09-09 15:08:12 +000079 OverloadedFunctionDecl *OvlTemplate
Douglas Gregorb7bfe792009-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 Stump11289f42009-09-09 15:08:12 +000089
Douglas Gregorb7bfe792009-09-02 22:59:36 +000090 return OvlTemplate;
91 }
92
93 return FuncTmpl;
94 }
95 }
Mike Stump11289f42009-09-09 15:08:12 +000096
Douglas Gregorb7bfe792009-09-02 22:59:36 +000097 return 0;
98}
99
100TemplateNameKind Sema::isTemplateName(Scope *S,
Mike Stump11289f42009-09-09 15:08:12 +0000101 const IdentifierInfo &II,
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000102 SourceLocation IdLoc,
Douglas Gregore861bac2009-08-25 22:51:20 +0000103 const CXXScopeSpec *SS,
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000104 TypeTy *ObjectTypePtr,
Douglas Gregore861bac2009-08-25 22:51:20 +0000105 bool EnteringContext,
Douglas Gregorb7bfe792009-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 Stump11289f42009-09-09 15:08:12 +0000113 assert((!SS || !SS->isSet()) &&
Douglas Gregorb7bfe792009-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 Stump11289f42009-09-09 15:08:12 +0000125
Douglas Gregorb7bfe792009-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 Stump11289f42009-09-09 15:08:12 +0000131 // expression or the declaration context associated with a prior
Douglas Gregorb7bfe792009-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 Stump11289f42009-09-09 15:08:12 +0000137
John McCall9f3059a2009-10-09 21:13:30 +0000138 LookupQualifiedName(Found, LookupCtx, &II, LookupOrdinaryName);
Mike Stump11289f42009-09-09 15:08:12 +0000139
Douglas Gregorb7bfe792009-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 Stump11289f42009-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 Gregorb7bfe792009-09-02 22:59:36 +0000145 // beginning of a template argument list (14.2) or a less-than operator.
Mike Stump11289f42009-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 Gregorb7bfe792009-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 McCall9f3059a2009-10-09 21:13:30 +0000153 LookupName(Found, S, &II, LookupOrdinaryName);
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000154 ObjectTypeSearchedInScope = true;
155 }
156 } else if (isDependent) {
Mike Stump11289f42009-09-09 15:08:12 +0000157 // We cannot look into a dependent object type or
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000158 return TNK_Non_template;
159 } else {
160 // Perform unqualified name lookup in the current scope.
John McCall9f3059a2009-10-09 21:13:30 +0000161 LookupName(Found, S, &II, LookupOrdinaryName);
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000162 }
Mike Stump11289f42009-09-09 15:08:12 +0000163
Douglas Gregore861bac2009-08-25 22:51:20 +0000164 // FIXME: Cope with ambiguous name-lookup results.
Mike Stump11289f42009-09-09 15:08:12 +0000165 assert(!Found.isAmbiguous() &&
Douglas Gregore861bac2009-08-25 22:51:20 +0000166 "Cannot handle template name-lookup ambiguities");
Douglas Gregordc572a32009-03-30 22:58:21 +0000167
John McCall9f3059a2009-10-09 21:13:30 +0000168 NamedDecl *Template
169 = isAcceptableTemplateName(Context, Found.getAsSingleDecl(Context));
Douglas Gregorb7bfe792009-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 Stump11289f42009-09-09 15:08:12 +0000175 // [...] If the lookup in the class of the object expression finds a
Douglas Gregorb7bfe792009-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 McCall9f3059a2009-10-09 21:13:30 +0000179 LookupResult FoundOuter;
180 LookupName(FoundOuter, S, &II, LookupOrdinaryName);
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000181 // FIXME: Handle ambiguities in this lookup better
John McCall9f3059a2009-10-09 21:13:30 +0000182 NamedDecl *OuterTemplate
183 = isAcceptableTemplateName(Context, FoundOuter.getAsSingleDecl(Context));
Mike Stump11289f42009-09-09 15:08:12 +0000184
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000185 if (!OuterTemplate) {
Mike Stump11289f42009-09-09 15:08:12 +0000186 // - if the name is not found, the name found in the class of the
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000187 // object expression is used, otherwise
188 } else if (!isa<ClassTemplateDecl>(OuterTemplate)) {
Mike Stump11289f42009-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 Gregorb7bfe792009-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 Stump11289f42009-09-09 15:08:12 +0000194 // entity as the one found in the class of the object expression,
Douglas Gregorb7bfe792009-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 Stump11289f42009-09-09 15:08:12 +0000202
203 // Recover by taking the template that we found in the object
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000204 // expression's type.
Douglas Gregor97f1f1c2009-03-26 00:10:35 +0000205 }
Mike Stump11289f42009-09-09 15:08:12 +0000206 }
Douglas Gregor55ad91f2008-12-18 19:37:40 +0000207 }
Mike Stump11289f42009-09-09 15:08:12 +0000208
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000209 if (SS && SS->isSet() && !SS->isInvalid()) {
Mike Stump11289f42009-09-09 15:08:12 +0000210 NestedNameSpecifier *Qualifier
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000211 = static_cast<NestedNameSpecifier *>(SS->getScopeRep());
Mike Stump11289f42009-09-09 15:08:12 +0000212 if (OverloadedFunctionDecl *Ovl
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000213 = dyn_cast<OverloadedFunctionDecl>(Template))
Mike Stump11289f42009-09-09 15:08:12 +0000214 TemplateResult
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000215 = TemplateTy::make(Context.getQualifiedTemplateName(Qualifier, false,
216 Ovl));
217 else
Mike Stump11289f42009-09-09 15:08:12 +0000218 TemplateResult
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000219 = TemplateTy::make(Context.getQualifiedTemplateName(Qualifier, false,
Mike Stump11289f42009-09-09 15:08:12 +0000220 cast<TemplateDecl>(Template)));
221 } else if (OverloadedFunctionDecl *Ovl
Douglas Gregorb7bfe792009-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 Stump11289f42009-09-09 15:08:12 +0000228
229 if (isa<ClassTemplateDecl>(Template) ||
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000230 isa<TemplateTemplateParmDecl>(Template))
231 return TNK_Type_template;
Mike Stump11289f42009-09-09 15:08:12 +0000232
233 assert((isa<FunctionTemplateDecl>(Template) ||
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000234 isa<OverloadedFunctionDecl>(Template)) &&
235 "Unhandled template kind in Sema::isTemplateName");
236 return TNK_Function_template;
Douglas Gregor55ad91f2008-12-18 19:37:40 +0000237}
238
Douglas Gregor5101c242008-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 Gregor5daeee22008-12-08 18:40:42 +0000244 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregor5101c242008-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 Stump11289f42009-09-09 15:08:12 +0000253 Diag(Loc, diag::err_template_param_shadow)
Douglas Gregor5101c242008-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 Gregor463421d2009-03-03 04:44:36 +0000259/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregorded2d7b2009-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 Lattner83f095c2009-03-28 19:18:32 +0000262TemplateDecl *Sema::AdjustDeclIfTemplate(DeclPtrTy &D) {
Douglas Gregor27c26e92009-10-06 21:27:51 +0000263 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D.getAs<Decl>())) {
Chris Lattner83f095c2009-03-28 19:18:32 +0000264 D = DeclPtrTy::make(Temp->getTemplatedDecl());
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000265 return Temp;
266 }
267 return 0;
268}
269
Douglas Gregor5101c242008-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 Stump11289f42009-09-09 15:08:12 +0000276/// ParamName is the location of the parameter name (if any).
Douglas Gregor5101c242008-12-05 18:15:24 +0000277/// If the type parameter has a default argument, it will be added
278/// later via ActOnTypeParameterDefault.
Mike Stump11289f42009-09-09 15:08:12 +0000279Sema::DeclPtrTy Sema::ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis,
Anders Carlsson01e9e932009-06-12 19:58:00 +0000280 SourceLocation EllipsisLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +0000281 SourceLocation KeyLoc,
282 IdentifierInfo *ParamName,
283 SourceLocation ParamNameLoc,
284 unsigned Depth, unsigned Position) {
Mike Stump11289f42009-09-09 15:08:12 +0000285 assert(S->isTemplateParamScope() &&
286 "Template type parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000287 bool Invalid = false;
288
289 if (ParamName) {
John McCall9f3059a2009-10-09 21:13:30 +0000290 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, LookupTagName);
Douglas Gregor5daeee22008-12-08 18:40:42 +0000291 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor5101c242008-12-05 18:15:24 +0000292 Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000293 PrevDecl);
Douglas Gregor5101c242008-12-05 18:15:24 +0000294 }
295
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000296 SourceLocation Loc = ParamNameLoc;
297 if (!ParamName)
298 Loc = KeyLoc;
299
Douglas Gregor5101c242008-12-05 18:15:24 +0000300 TemplateTypeParmDecl *Param
Mike Stump11289f42009-09-09 15:08:12 +0000301 = TemplateTypeParmDecl::Create(Context, CurContext, Loc,
302 Depth, Position, ParamName, Typename,
Anders Carlssonfb1d7762009-06-12 22:23:22 +0000303 Ellipsis);
Douglas Gregor5101c242008-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 Lattner83f095c2009-03-28 19:18:32 +0000309 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor5101c242008-12-05 18:15:24 +0000310 IdResolver.AddDecl(Param);
311 }
312
Chris Lattner83f095c2009-03-28 19:18:32 +0000313 return DeclPtrTy::make(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000314}
315
Douglas Gregordba32632009-02-10 19:49:53 +0000316/// ActOnTypeParameterDefault - Adds a default argument (the type
Mike Stump11289f42009-09-09 15:08:12 +0000317/// Default) to the given template type parameter (TypeParam).
318void Sema::ActOnTypeParameterDefault(DeclPtrTy TypeParam,
Douglas Gregordba32632009-02-10 19:49:53 +0000319 SourceLocation EqualLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000320 SourceLocation DefaultLoc,
Douglas Gregordba32632009-02-10 19:49:53 +0000321 TypeTy *DefaultT) {
Mike Stump11289f42009-09-09 15:08:12 +0000322 TemplateTypeParmDecl *Parm
Chris Lattner83f095c2009-03-28 19:18:32 +0000323 = cast<TemplateTypeParmDecl>(TypeParam.getAs<Decl>());
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +0000324 // FIXME: Preserve type source info.
325 QualType Default = GetTypeFromParser(DefaultT);
Douglas Gregordba32632009-02-10 19:49:53 +0000326
Anders Carlssond3824352009-06-12 22:30:13 +0000327 // C++0x [temp.param]p9:
328 // A default template-argument may be specified for any kind of
Mike Stump11289f42009-09-09 15:08:12 +0000329 // template-parameter that is not a template parameter pack.
Anders Carlssond3824352009-06-12 22:30:13 +0000330 if (Parm->isParameterPack()) {
331 Diag(DefaultLoc, diag::err_template_param_pack_default_arg);
Anders Carlssond3824352009-06-12 22:30:13 +0000332 return;
333 }
Mike Stump11289f42009-09-09 15:08:12 +0000334
Douglas Gregordba32632009-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 Stump11289f42009-09-09 15:08:12 +0000338
Douglas Gregordba32632009-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 Gregor463421d2009-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 Stump11289f42009-09-09 15:08:12 +0000353QualType
Douglas Gregor463421d2009-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 Stump11289f42009-09-09 15:08:12 +0000362 // -- pointer to object or pointer to function,
363 (T->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000364 (T->getAs<PointerType>()->getPointeeType()->isObjectType() ||
365 T->getAs<PointerType>()->getPointeeType()->isFunctionType())) ||
Mike Stump11289f42009-09-09 15:08:12 +0000366 // -- reference to object or reference to function,
Douglas Gregor463421d2009-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 Gregor5101c242008-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 Lattner83f095c2009-03-28 19:18:32 +0000396Sema::DeclPtrTy Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
Mike Stump11289f42009-09-09 15:08:12 +0000397 unsigned Depth,
Chris Lattner83f095c2009-03-28 19:18:32 +0000398 unsigned Position) {
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +0000399 DeclaratorInfo *DInfo = 0;
400 QualType T = GetTypeForDeclarator(D, S, &DInfo);
Douglas Gregor5101c242008-12-05 18:15:24 +0000401
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000402 assert(S->isTemplateParamScope() &&
403 "Non-type template parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000404 bool Invalid = false;
405
406 IdentifierInfo *ParamName = D.getIdentifier();
407 if (ParamName) {
John McCall9f3059a2009-10-09 21:13:30 +0000408 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, LookupTagName);
Douglas Gregor5daeee22008-12-08 18:40:42 +0000409 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor5101c242008-12-05 18:15:24 +0000410 Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000411 PrevDecl);
Douglas Gregor5101c242008-12-05 18:15:24 +0000412 }
413
Douglas Gregor463421d2009-03-03 04:44:36 +0000414 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
Douglas Gregorce0fc86f2009-03-09 16:46:39 +0000415 if (T.isNull()) {
Douglas Gregor463421d2009-03-03 04:44:36 +0000416 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregorce0fc86f2009-03-09 16:46:39 +0000417 Invalid = true;
418 }
Douglas Gregor81338792009-02-10 17:43:50 +0000419
Douglas Gregor5101c242008-12-05 18:15:24 +0000420 NonTypeTemplateParmDecl *Param
421 = NonTypeTemplateParmDecl::Create(Context, CurContext, D.getIdentifierLoc(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +0000422 Depth, Position, ParamName, T, DInfo);
Douglas Gregor5101c242008-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 Lattner83f095c2009-03-28 19:18:32 +0000428 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor5101c242008-12-05 18:15:24 +0000429 IdResolver.AddDecl(Param);
430 }
Chris Lattner83f095c2009-03-28 19:18:32 +0000431 return DeclPtrTy::make(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000432}
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000433
Douglas Gregordba32632009-02-10 19:49:53 +0000434/// \brief Adds a default argument to the given non-type template
435/// parameter.
Chris Lattner83f095c2009-03-28 19:18:32 +0000436void Sema::ActOnNonTypeTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregordba32632009-02-10 19:49:53 +0000437 SourceLocation EqualLoc,
438 ExprArg DefaultE) {
Mike Stump11289f42009-09-09 15:08:12 +0000439 NonTypeTemplateParmDecl *TemplateParm
Chris Lattner83f095c2009-03-28 19:18:32 +0000440 = cast<NonTypeTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregordba32632009-02-10 19:49:53 +0000441 Expr *Default = static_cast<Expr *>(DefaultE.get());
Mike Stump11289f42009-09-09 15:08:12 +0000442
Douglas Gregordba32632009-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 Stump11289f42009-09-09 15:08:12 +0000446
Douglas Gregordba32632009-02-10 19:49:53 +0000447 // Check the well-formedness of the default template argument.
Douglas Gregor74eba0b2009-06-11 18:10:32 +0000448 TemplateArgument Converted;
449 if (CheckTemplateArgument(TemplateParm, TemplateParm->getType(), Default,
450 Converted)) {
Douglas Gregordba32632009-02-10 19:49:53 +0000451 TemplateParm->setInvalidDecl();
452 return;
453 }
454
Anders Carlssonb781bcd2009-05-01 19:49:17 +0000455 TemplateParm->setDefaultArgument(DefaultE.takeAs<Expr>());
Douglas Gregordba32632009-02-10 19:49:53 +0000456}
457
Douglas Gregorded2d7b2009-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 Lattner83f095c2009-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 Stump11289f42009-09-09 15:08:12 +0000468 unsigned Position) {
Douglas Gregorded2d7b2009-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 Lattner83f095c2009-03-28 19:18:32 +0000490 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000491 IdResolver.AddDecl(Param);
492 }
493
Chris Lattner83f095c2009-03-28 19:18:32 +0000494 return DeclPtrTy::make(Param);
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000495}
496
Douglas Gregordba32632009-02-10 19:49:53 +0000497/// \brief Adds a default argument to the given template template
498/// parameter.
Chris Lattner83f095c2009-03-28 19:18:32 +0000499void Sema::ActOnTemplateTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregordba32632009-02-10 19:49:53 +0000500 SourceLocation EqualLoc,
501 ExprArg DefaultE) {
Mike Stump11289f42009-09-09 15:08:12 +0000502 TemplateTemplateParmDecl *TemplateParm
Chris Lattner83f095c2009-03-28 19:18:32 +0000503 = cast<TemplateTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregordba32632009-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 Stump11289f42009-09-09 15:08:12 +0000507 DeclRefExpr *Default
Douglas Gregordba32632009-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 Stump11289f42009-09-09 15:08:12 +0000516 Diag(Default->getSourceRange().getBegin(),
Douglas Gregordba32632009-02-10 19:49:53 +0000517 diag::err_template_arg_must_be_template)
518 << Default->getSourceRange();
519 TemplateParm->setInvalidDecl();
520 return;
Mike Stump11289f42009-09-09 15:08:12 +0000521 }
Douglas Gregordba32632009-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 Gregorb9bd8a92008-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 Stump11289f42009-09-09 15:08:12 +0000536 SourceLocation TemplateLoc,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000537 SourceLocation LAngleLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +0000538 DeclPtrTy *Params, unsigned NumParams,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000539 SourceLocation RAngleLoc) {
540 if (ExportLoc.isValid())
541 Diag(ExportLoc, diag::note_template_export_unsupported);
542
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000543 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
Douglas Gregorbe999392009-09-15 16:23:51 +0000544 (NamedDecl**)Params, NumParams,
545 RAngleLoc);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000546}
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000547
Douglas Gregorc08f4892009-03-25 00:13:59 +0000548Sema::DeclResult
John McCall9bb74a52009-07-31 02:45:11 +0000549Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000550 SourceLocation KWLoc, const CXXScopeSpec &SS,
551 IdentifierInfo *Name, SourceLocation NameLoc,
552 AttributeList *Attr,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000553 TemplateParameterList *TemplateParams,
Anders Carlssondfbbdf62009-03-26 00:52:18 +0000554 AccessSpecifier AS) {
Mike Stump11289f42009-09-09 15:08:12 +0000555 assert(TemplateParams && TemplateParams->size() > 0 &&
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000556 "No template parameters");
John McCall9bb74a52009-07-31 02:45:11 +0000557 assert(TUK != TUK_Reference && "Can only declare or define class templates");
Douglas Gregordba32632009-02-10 19:49:53 +0000558 bool Invalid = false;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000559
560 // Check that we can declare a template here.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000561 if (CheckTemplateDeclScope(S, TemplateParams))
Douglas Gregorc08f4892009-03-25 00:13:59 +0000562 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000563
John McCall27b5c252009-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 Gregorcd72ba92009-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 Gregorc08f4892009-03-25 00:13:59 +0000570 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000571 }
572
573 // Find any previous declaration with this name.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000574 DeclContext *SemanticContext;
575 LookupResult Previous;
576 if (SS.isNotEmpty() && !SS.isInvalid()) {
577 SemanticContext = computeDeclContext(SS, true);
578 if (!SemanticContext) {
579 // FIXME: Produce a reasonable diagnostic here
580 return true;
581 }
Mike Stump11289f42009-09-09 15:08:12 +0000582
John McCall9f3059a2009-10-09 21:13:30 +0000583 LookupQualifiedName(Previous, SemanticContext, Name, LookupOrdinaryName,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000584 true);
585 } else {
586 SemanticContext = CurContext;
John McCall9f3059a2009-10-09 21:13:30 +0000587 LookupName(Previous, S, Name, LookupOrdinaryName, true);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000588 }
Mike Stump11289f42009-09-09 15:08:12 +0000589
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000590 assert(!Previous.isAmbiguous() && "Ambiguity in class template redecl?");
591 NamedDecl *PrevDecl = 0;
592 if (Previous.begin() != Previous.end())
593 PrevDecl = *Previous.begin();
594
Douglas Gregor9acb6902009-09-26 07:05:09 +0000595 if (PrevDecl && TUK == TUK_Friend) {
596 // C++ [namespace.memdef]p3:
597 // [...] When looking for a prior declaration of a class or a function
598 // declared as a friend, and when the name of the friend class or
599 // function is neither a qualified name nor a template-id, scopes outside
600 // the innermost enclosing namespace scope are not considered.
601 DeclContext *OutermostContext = CurContext;
602 while (!OutermostContext->isFileContext())
603 OutermostContext = OutermostContext->getLookupParent();
604
605 if (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
606 OutermostContext->Encloses(PrevDecl->getDeclContext())) {
607 SemanticContext = PrevDecl->getDeclContext();
608 } else {
609 // Declarations in outer scopes don't matter. However, the outermost
610 // context we computed is the semntic context for our new
611 // declaration.
612 PrevDecl = 0;
613 SemanticContext = OutermostContext;
614 }
615 } else if (PrevDecl && !isDeclInScope(PrevDecl, SemanticContext, S))
Douglas Gregorf187420f2009-06-17 23:37:01 +0000616 PrevDecl = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000617
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000618 // If there is a previous declaration with the same name, check
619 // whether this is a valid redeclaration.
Mike Stump11289f42009-09-09 15:08:12 +0000620 ClassTemplateDecl *PrevClassTemplate
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000621 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
Douglas Gregor7f34bae2009-10-09 21:11:42 +0000622
623 // We may have found the injected-class-name of a class template,
624 // class template partial specialization, or class template specialization.
625 // In these cases, grab the template that is being defined or specialized.
626 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
627 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
628 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
629 PrevClassTemplate
630 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
631 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
632 PrevClassTemplate
633 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
634 ->getSpecializedTemplate();
635 }
636 }
637
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000638 if (PrevClassTemplate) {
639 // Ensure that the template parameter lists are compatible.
640 if (!TemplateParameterListsAreEqual(TemplateParams,
641 PrevClassTemplate->getTemplateParameters(),
642 /*Complain=*/true))
Douglas Gregorc08f4892009-03-25 00:13:59 +0000643 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000644
645 // C++ [temp.class]p4:
646 // In a redeclaration, partial specialization, explicit
647 // specialization or explicit instantiation of a class template,
648 // the class-key shall agree in kind with the original class
649 // template declaration (7.1.5.3).
650 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Douglas Gregord9034f02009-05-14 16:41:31 +0000651 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind, KWLoc, *Name)) {
Mike Stump11289f42009-09-09 15:08:12 +0000652 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +0000653 << Name
Mike Stump11289f42009-09-09 15:08:12 +0000654 << CodeModificationHint::CreateReplacement(KWLoc,
Douglas Gregor170512f2009-04-01 23:51:29 +0000655 PrevRecordDecl->getKindName());
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000656 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregor170512f2009-04-01 23:51:29 +0000657 Kind = PrevRecordDecl->getTagKind();
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000658 }
659
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000660 // Check for redefinition of this class template.
John McCall9bb74a52009-07-31 02:45:11 +0000661 if (TUK == TUK_Definition) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000662 if (TagDecl *Def = PrevRecordDecl->getDefinition(Context)) {
663 Diag(NameLoc, diag::err_redefinition) << Name;
664 Diag(Def->getLocation(), diag::note_previous_definition);
665 // FIXME: Would it make sense to try to "forget" the previous
666 // definition, as part of error recovery?
Douglas Gregorc08f4892009-03-25 00:13:59 +0000667 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000668 }
669 }
670 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
671 // Maybe we will complain about the shadowed template parameter.
672 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
673 // Just pretend that we didn't see the previous declaration.
674 PrevDecl = 0;
675 } else if (PrevDecl) {
676 // C++ [temp]p5:
677 // A class template shall not have the same name as any other
678 // template, class, function, object, enumeration, enumerator,
679 // namespace, or type in the same scope (3.3), except as specified
680 // in (14.5.4).
681 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
682 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregorc08f4892009-03-25 00:13:59 +0000683 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000684 }
685
Douglas Gregordba32632009-02-10 19:49:53 +0000686 // Check the template parameter list of this declaration, possibly
687 // merging in the template parameter list from the previous class
688 // template declaration.
689 if (CheckTemplateParameterList(TemplateParams,
690 PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0))
691 Invalid = true;
Mike Stump11289f42009-09-09 15:08:12 +0000692
Douglas Gregore362cea2009-05-10 22:57:19 +0000693 // FIXME: If we had a scope specifier, we better have a previous template
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000694 // declaration!
695
Mike Stump11289f42009-09-09 15:08:12 +0000696 CXXRecordDecl *NewClass =
Douglas Gregor82fe3e32009-07-21 14:46:17 +0000697 CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name, KWLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000698 PrevClassTemplate?
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000699 PrevClassTemplate->getTemplatedDecl() : 0,
700 /*DelayTypeCreation=*/true);
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000701
702 ClassTemplateDecl *NewTemplate
703 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
704 DeclarationName(Name), TemplateParams,
Douglas Gregor90a1a652009-03-19 17:26:29 +0000705 NewClass, PrevClassTemplate);
Douglas Gregor97f1f1c2009-03-26 00:10:35 +0000706 NewClass->setDescribedClassTemplate(NewTemplate);
707
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000708 // Build the type for the class template declaration now.
Mike Stump11289f42009-09-09 15:08:12 +0000709 QualType T =
710 Context.getTypeDeclType(NewClass,
711 PrevClassTemplate?
712 PrevClassTemplate->getTemplatedDecl() : 0);
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000713 assert(T->isDependentType() && "Class template type is not dependent?");
714 (void)T;
715
Anders Carlsson137108d2009-03-26 01:24:28 +0000716 // Set the access specifier.
Douglas Gregor3dad8422009-09-26 06:47:28 +0000717 if (!Invalid && TUK != TUK_Friend)
John McCall27b5c252009-09-14 21:59:20 +0000718 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
Mike Stump11289f42009-09-09 15:08:12 +0000719
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000720 // Set the lexical context of these templates
721 NewClass->setLexicalDeclContext(CurContext);
722 NewTemplate->setLexicalDeclContext(CurContext);
723
John McCall9bb74a52009-07-31 02:45:11 +0000724 if (TUK == TUK_Definition)
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000725 NewClass->startDefinition();
726
727 if (Attr)
Douglas Gregor758a8692009-06-17 21:51:59 +0000728 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000729
John McCall27b5c252009-09-14 21:59:20 +0000730 if (TUK != TUK_Friend)
731 PushOnScopeChains(NewTemplate, S);
732 else {
Douglas Gregor3dad8422009-09-26 06:47:28 +0000733 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
John McCall27b5c252009-09-14 21:59:20 +0000734 NewTemplate->setAccess(PrevClassTemplate->getAccess());
Douglas Gregor3dad8422009-09-26 06:47:28 +0000735 NewClass->setAccess(PrevClassTemplate->getAccess());
736 }
John McCall27b5c252009-09-14 21:59:20 +0000737
Douglas Gregor3dad8422009-09-26 06:47:28 +0000738 NewTemplate->setObjectOfFriendDecl(/* PreviouslyDeclared = */
739 PrevClassTemplate != NULL);
740
John McCall27b5c252009-09-14 21:59:20 +0000741 // Friend templates are visible in fairly strange ways.
742 if (!CurContext->isDependentContext()) {
743 DeclContext *DC = SemanticContext->getLookupContext();
744 DC->makeDeclVisibleInContext(NewTemplate, /* Recoverable = */ false);
745 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
746 PushOnScopeChains(NewTemplate, EnclosingScope,
747 /* AddToContext = */ false);
748 }
Douglas Gregor3dad8422009-09-26 06:47:28 +0000749
750 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
751 NewClass->getLocation(),
752 NewTemplate,
753 /*FIXME:*/NewClass->getLocation());
754 Friend->setAccess(AS_public);
755 CurContext->addDecl(Friend);
John McCall27b5c252009-09-14 21:59:20 +0000756 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000757
Douglas Gregordba32632009-02-10 19:49:53 +0000758 if (Invalid) {
759 NewTemplate->setInvalidDecl();
760 NewClass->setInvalidDecl();
761 }
Chris Lattner83f095c2009-03-28 19:18:32 +0000762 return DeclPtrTy::make(NewTemplate);
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000763}
764
Douglas Gregordba32632009-02-10 19:49:53 +0000765/// \brief Checks the validity of a template parameter list, possibly
766/// considering the template parameter list from a previous
767/// declaration.
768///
769/// If an "old" template parameter list is provided, it must be
770/// equivalent (per TemplateParameterListsAreEqual) to the "new"
771/// template parameter list.
772///
773/// \param NewParams Template parameter list for a new template
774/// declaration. This template parameter list will be updated with any
775/// default arguments that are carried through from the previous
776/// template parameter list.
777///
778/// \param OldParams If provided, template parameter list from a
779/// previous declaration of the same template. Default template
780/// arguments will be merged from the old template parameter list to
781/// the new template parameter list.
782///
783/// \returns true if an error occurred, false otherwise.
784bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
785 TemplateParameterList *OldParams) {
786 bool Invalid = false;
Mike Stump11289f42009-09-09 15:08:12 +0000787
Douglas Gregordba32632009-02-10 19:49:53 +0000788 // C++ [temp.param]p10:
789 // The set of default template-arguments available for use with a
790 // template declaration or definition is obtained by merging the
791 // default arguments from the definition (if in scope) and all
792 // declarations in scope in the same way default function
793 // arguments are (8.3.6).
794 bool SawDefaultArgument = false;
795 SourceLocation PreviousDefaultArgLoc;
Douglas Gregord32e0282009-02-09 23:23:08 +0000796
Anders Carlsson327865d2009-06-12 23:20:15 +0000797 bool SawParameterPack = false;
798 SourceLocation ParameterPackLoc;
799
Mike Stumpc89c8e32009-02-11 23:03:27 +0000800 // Dummy initialization to avoid warnings.
Douglas Gregor5bd22da2009-02-11 20:46:19 +0000801 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregordba32632009-02-10 19:49:53 +0000802 if (OldParams)
803 OldParam = OldParams->begin();
804
805 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
806 NewParamEnd = NewParams->end();
807 NewParam != NewParamEnd; ++NewParam) {
808 // Variables used to diagnose redundant default arguments
809 bool RedundantDefaultArg = false;
810 SourceLocation OldDefaultLoc;
811 SourceLocation NewDefaultLoc;
812
813 // Variables used to diagnose missing default arguments
814 bool MissingDefaultArg = false;
815
Anders Carlsson327865d2009-06-12 23:20:15 +0000816 // C++0x [temp.param]p11:
817 // If a template parameter of a class template is a template parameter pack,
818 // it must be the last template parameter.
819 if (SawParameterPack) {
Mike Stump11289f42009-09-09 15:08:12 +0000820 Diag(ParameterPackLoc,
Anders Carlsson327865d2009-06-12 23:20:15 +0000821 diag::err_template_param_pack_must_be_last_template_parameter);
822 Invalid = true;
823 }
824
Douglas Gregordba32632009-02-10 19:49:53 +0000825 // Merge default arguments for template type parameters.
826 if (TemplateTypeParmDecl *NewTypeParm
827 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
Mike Stump11289f42009-09-09 15:08:12 +0000828 TemplateTypeParmDecl *OldTypeParm
Douglas Gregordba32632009-02-10 19:49:53 +0000829 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +0000830
Anders Carlsson327865d2009-06-12 23:20:15 +0000831 if (NewTypeParm->isParameterPack()) {
832 assert(!NewTypeParm->hasDefaultArgument() &&
833 "Parameter packs can't have a default argument!");
834 SawParameterPack = true;
835 ParameterPackLoc = NewTypeParm->getLocation();
Mike Stump11289f42009-09-09 15:08:12 +0000836 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
Douglas Gregordba32632009-02-10 19:49:53 +0000837 NewTypeParm->hasDefaultArgument()) {
838 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
839 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
840 SawDefaultArgument = true;
841 RedundantDefaultArg = true;
842 PreviousDefaultArgLoc = NewDefaultLoc;
843 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
844 // Merge the default argument from the old declaration to the
845 // new declaration.
846 SawDefaultArgument = true;
847 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgument(),
848 OldTypeParm->getDefaultArgumentLoc(),
849 true);
850 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
851 } else if (NewTypeParm->hasDefaultArgument()) {
852 SawDefaultArgument = true;
853 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
854 } else if (SawDefaultArgument)
855 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +0000856 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
Douglas Gregordba32632009-02-10 19:49:53 +0000857 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000858 // Merge default arguments for non-type template parameters
Douglas Gregordba32632009-02-10 19:49:53 +0000859 NonTypeTemplateParmDecl *OldNonTypeParm
860 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +0000861 if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
Douglas Gregordba32632009-02-10 19:49:53 +0000862 NewNonTypeParm->hasDefaultArgument()) {
863 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
864 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
865 SawDefaultArgument = true;
866 RedundantDefaultArg = true;
867 PreviousDefaultArgLoc = NewDefaultLoc;
868 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
869 // Merge the default argument from the old declaration to the
870 // new declaration.
871 SawDefaultArgument = true;
872 // FIXME: We need to create a new kind of "default argument"
873 // expression that points to a previous template template
874 // parameter.
875 NewNonTypeParm->setDefaultArgument(
876 OldNonTypeParm->getDefaultArgument());
877 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
878 } else if (NewNonTypeParm->hasDefaultArgument()) {
879 SawDefaultArgument = true;
880 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
881 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +0000882 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +0000883 } else {
Douglas Gregordba32632009-02-10 19:49:53 +0000884 // Merge default arguments for template template parameters
Douglas Gregordba32632009-02-10 19:49:53 +0000885 TemplateTemplateParmDecl *NewTemplateParm
886 = cast<TemplateTemplateParmDecl>(*NewParam);
887 TemplateTemplateParmDecl *OldTemplateParm
888 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +0000889 if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
Douglas Gregordba32632009-02-10 19:49:53 +0000890 NewTemplateParm->hasDefaultArgument()) {
891 OldDefaultLoc = OldTemplateParm->getDefaultArgumentLoc();
892 NewDefaultLoc = NewTemplateParm->getDefaultArgumentLoc();
893 SawDefaultArgument = true;
894 RedundantDefaultArg = true;
895 PreviousDefaultArgLoc = NewDefaultLoc;
896 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
897 // Merge the default argument from the old declaration to the
898 // new declaration.
899 SawDefaultArgument = true;
Mike Stump87c57ac2009-05-16 07:39:55 +0000900 // FIXME: We need to create a new kind of "default argument" expression
901 // that points to a previous template template parameter.
Douglas Gregordba32632009-02-10 19:49:53 +0000902 NewTemplateParm->setDefaultArgument(
903 OldTemplateParm->getDefaultArgument());
904 PreviousDefaultArgLoc = OldTemplateParm->getDefaultArgumentLoc();
905 } else if (NewTemplateParm->hasDefaultArgument()) {
906 SawDefaultArgument = true;
907 PreviousDefaultArgLoc = NewTemplateParm->getDefaultArgumentLoc();
908 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +0000909 MissingDefaultArg = true;
Douglas Gregordba32632009-02-10 19:49:53 +0000910 }
911
912 if (RedundantDefaultArg) {
913 // C++ [temp.param]p12:
914 // A template-parameter shall not be given default arguments
915 // by two different declarations in the same scope.
916 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
917 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
918 Invalid = true;
919 } else if (MissingDefaultArg) {
920 // C++ [temp.param]p11:
921 // If a template-parameter has a default template-argument,
922 // all subsequent template-parameters shall have a default
923 // template-argument supplied.
Mike Stump11289f42009-09-09 15:08:12 +0000924 Diag((*NewParam)->getLocation(),
Douglas Gregordba32632009-02-10 19:49:53 +0000925 diag::err_template_param_default_arg_missing);
926 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
927 Invalid = true;
928 }
929
930 // If we have an old template parameter list that we're merging
931 // in, move on to the next parameter.
932 if (OldParams)
933 ++OldParam;
934 }
935
936 return Invalid;
937}
Douglas Gregord32e0282009-02-09 23:23:08 +0000938
Mike Stump11289f42009-09-09 15:08:12 +0000939/// \brief Match the given template parameter lists to the given scope
Douglas Gregord8d297c2009-07-21 23:53:31 +0000940/// specifier, returning the template parameter list that applies to the
941/// name.
942///
943/// \param DeclStartLoc the start of the declaration that has a scope
944/// specifier or a template parameter list.
Mike Stump11289f42009-09-09 15:08:12 +0000945///
Douglas Gregord8d297c2009-07-21 23:53:31 +0000946/// \param SS the scope specifier that will be matched to the given template
947/// parameter lists. This scope specifier precedes a qualified name that is
948/// being declared.
949///
950/// \param ParamLists the template parameter lists, from the outermost to the
951/// innermost template parameter lists.
952///
953/// \param NumParamLists the number of template parameter lists in ParamLists.
954///
Douglas Gregor5c0405d2009-10-07 22:35:40 +0000955/// \param IsExplicitSpecialization will be set true if the entity being
956/// declared is an explicit specialization, false otherwise.
957///
Mike Stump11289f42009-09-09 15:08:12 +0000958/// \returns the template parameter list, if any, that corresponds to the
Douglas Gregord8d297c2009-07-21 23:53:31 +0000959/// name that is preceded by the scope specifier @p SS. This template
960/// parameter list may be have template parameters (if we're declaring a
Mike Stump11289f42009-09-09 15:08:12 +0000961/// template) or may have no template parameters (if we're declaring a
Douglas Gregord8d297c2009-07-21 23:53:31 +0000962/// template specialization), or may be NULL (if we were's declaring isn't
963/// itself a template).
964TemplateParameterList *
965Sema::MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc,
966 const CXXScopeSpec &SS,
967 TemplateParameterList **ParamLists,
Douglas Gregor5c0405d2009-10-07 22:35:40 +0000968 unsigned NumParamLists,
969 bool &IsExplicitSpecialization) {
970 IsExplicitSpecialization = false;
971
Douglas Gregord8d297c2009-07-21 23:53:31 +0000972 // Find the template-ids that occur within the nested-name-specifier. These
973 // template-ids will match up with the template parameter lists.
974 llvm::SmallVector<const TemplateSpecializationType *, 4>
975 TemplateIdsInSpecifier;
976 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
977 NNS; NNS = NNS->getPrefix()) {
Mike Stump11289f42009-09-09 15:08:12 +0000978 if (const TemplateSpecializationType *SpecType
Douglas Gregord8d297c2009-07-21 23:53:31 +0000979 = dyn_cast_or_null<TemplateSpecializationType>(NNS->getAsType())) {
980 TemplateDecl *Template = SpecType->getTemplateName().getAsTemplateDecl();
981 if (!Template)
982 continue; // FIXME: should this be an error? probably...
Mike Stump11289f42009-09-09 15:08:12 +0000983
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000984 if (const RecordType *Record = SpecType->getAs<RecordType>()) {
Douglas Gregord8d297c2009-07-21 23:53:31 +0000985 ClassTemplateSpecializationDecl *SpecDecl
986 = cast<ClassTemplateSpecializationDecl>(Record->getDecl());
987 // If the nested name specifier refers to an explicit specialization,
988 // we don't need a template<> header.
Douglas Gregor82e22862009-09-16 00:01:48 +0000989 // FIXME: revisit this approach once we cope with specializations
Douglas Gregor15301382009-07-30 17:40:51 +0000990 // properly.
Douglas Gregord8d297c2009-07-21 23:53:31 +0000991 if (SpecDecl->getSpecializationKind() == TSK_ExplicitSpecialization)
992 continue;
993 }
Mike Stump11289f42009-09-09 15:08:12 +0000994
Douglas Gregord8d297c2009-07-21 23:53:31 +0000995 TemplateIdsInSpecifier.push_back(SpecType);
996 }
997 }
Mike Stump11289f42009-09-09 15:08:12 +0000998
Douglas Gregord8d297c2009-07-21 23:53:31 +0000999 // Reverse the list of template-ids in the scope specifier, so that we can
1000 // more easily match up the template-ids and the template parameter lists.
1001 std::reverse(TemplateIdsInSpecifier.begin(), TemplateIdsInSpecifier.end());
Mike Stump11289f42009-09-09 15:08:12 +00001002
Douglas Gregord8d297c2009-07-21 23:53:31 +00001003 SourceLocation FirstTemplateLoc = DeclStartLoc;
1004 if (NumParamLists)
1005 FirstTemplateLoc = ParamLists[0]->getTemplateLoc();
Mike Stump11289f42009-09-09 15:08:12 +00001006
Douglas Gregord8d297c2009-07-21 23:53:31 +00001007 // Match the template-ids found in the specifier to the template parameter
1008 // lists.
1009 unsigned Idx = 0;
1010 for (unsigned NumTemplateIds = TemplateIdsInSpecifier.size();
1011 Idx != NumTemplateIds; ++Idx) {
Douglas Gregor15301382009-07-30 17:40:51 +00001012 QualType TemplateId = QualType(TemplateIdsInSpecifier[Idx], 0);
1013 bool DependentTemplateId = TemplateId->isDependentType();
Douglas Gregord8d297c2009-07-21 23:53:31 +00001014 if (Idx >= NumParamLists) {
1015 // We have a template-id without a corresponding template parameter
1016 // list.
1017 if (DependentTemplateId) {
Mike Stump11289f42009-09-09 15:08:12 +00001018 // FIXME: the location information here isn't great.
1019 Diag(SS.getRange().getBegin(),
Douglas Gregord8d297c2009-07-21 23:53:31 +00001020 diag::err_template_spec_needs_template_parameters)
Douglas Gregor15301382009-07-30 17:40:51 +00001021 << TemplateId
Douglas Gregord8d297c2009-07-21 23:53:31 +00001022 << SS.getRange();
1023 } else {
1024 Diag(SS.getRange().getBegin(), diag::err_template_spec_needs_header)
1025 << SS.getRange()
1026 << CodeModificationHint::CreateInsertion(FirstTemplateLoc,
1027 "template<> ");
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001028 IsExplicitSpecialization = true;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001029 }
1030 return 0;
1031 }
Mike Stump11289f42009-09-09 15:08:12 +00001032
Douglas Gregord8d297c2009-07-21 23:53:31 +00001033 // Check the template parameter list against its corresponding template-id.
Douglas Gregor15301382009-07-30 17:40:51 +00001034 if (DependentTemplateId) {
Mike Stump11289f42009-09-09 15:08:12 +00001035 TemplateDecl *Template
Douglas Gregor15301382009-07-30 17:40:51 +00001036 = TemplateIdsInSpecifier[Idx]->getTemplateName().getAsTemplateDecl();
1037
Mike Stump11289f42009-09-09 15:08:12 +00001038 if (ClassTemplateDecl *ClassTemplate
Douglas Gregor15301382009-07-30 17:40:51 +00001039 = dyn_cast<ClassTemplateDecl>(Template)) {
1040 TemplateParameterList *ExpectedTemplateParams = 0;
1041 // Is this template-id naming the primary template?
1042 if (Context.hasSameType(TemplateId,
1043 ClassTemplate->getInjectedClassNameType(Context)))
1044 ExpectedTemplateParams = ClassTemplate->getTemplateParameters();
1045 // ... or a partial specialization?
1046 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
1047 = ClassTemplate->findPartialSpecialization(TemplateId))
1048 ExpectedTemplateParams = PartialSpec->getTemplateParameters();
1049
1050 if (ExpectedTemplateParams)
Mike Stump11289f42009-09-09 15:08:12 +00001051 TemplateParameterListsAreEqual(ParamLists[Idx],
Douglas Gregor15301382009-07-30 17:40:51 +00001052 ExpectedTemplateParams,
1053 true);
Mike Stump11289f42009-09-09 15:08:12 +00001054 }
Douglas Gregor15301382009-07-30 17:40:51 +00001055 } else if (ParamLists[Idx]->size() > 0)
Mike Stump11289f42009-09-09 15:08:12 +00001056 Diag(ParamLists[Idx]->getTemplateLoc(),
Douglas Gregor15301382009-07-30 17:40:51 +00001057 diag::err_template_param_list_matches_nontemplate)
1058 << TemplateId
1059 << ParamLists[Idx]->getSourceRange();
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001060 else
1061 IsExplicitSpecialization = true;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001062 }
Mike Stump11289f42009-09-09 15:08:12 +00001063
Douglas Gregord8d297c2009-07-21 23:53:31 +00001064 // If there were at least as many template-ids as there were template
1065 // parameter lists, then there are no template parameter lists remaining for
1066 // the declaration itself.
1067 if (Idx >= NumParamLists)
1068 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001069
Douglas Gregord8d297c2009-07-21 23:53:31 +00001070 // If there were too many template parameter lists, complain about that now.
1071 if (Idx != NumParamLists - 1) {
1072 while (Idx < NumParamLists - 1) {
Mike Stump11289f42009-09-09 15:08:12 +00001073 Diag(ParamLists[Idx]->getTemplateLoc(),
Douglas Gregord8d297c2009-07-21 23:53:31 +00001074 diag::err_template_spec_extra_headers)
1075 << SourceRange(ParamLists[Idx]->getTemplateLoc(),
1076 ParamLists[Idx]->getRAngleLoc());
1077 ++Idx;
1078 }
1079 }
Mike Stump11289f42009-09-09 15:08:12 +00001080
Douglas Gregord8d297c2009-07-21 23:53:31 +00001081 // Return the last template parameter list, which corresponds to the
1082 // entity being declared.
1083 return ParamLists[NumParamLists - 1];
1084}
1085
Douglas Gregorc40290e2009-03-09 23:48:35 +00001086/// \brief Translates template arguments as provided by the parser
1087/// into template arguments used by semantic analysis.
Douglas Gregor0e876e02009-09-25 23:53:26 +00001088void Sema::translateTemplateArguments(ASTTemplateArgsPtr &TemplateArgsIn,
1089 SourceLocation *TemplateArgLocs,
Douglas Gregorc40290e2009-03-09 23:48:35 +00001090 llvm::SmallVector<TemplateArgument, 16> &TemplateArgs) {
1091 TemplateArgs.reserve(TemplateArgsIn.size());
1092
1093 void **Args = TemplateArgsIn.getArgs();
1094 bool *ArgIsType = TemplateArgsIn.getArgIsType();
1095 for (unsigned Arg = 0, Last = TemplateArgsIn.size(); Arg != Last; ++Arg) {
1096 TemplateArgs.push_back(
1097 ArgIsType[Arg]? TemplateArgument(TemplateArgLocs[Arg],
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00001098 //FIXME: Preserve type source info.
1099 Sema::GetTypeFromParser(Args[Arg]))
Douglas Gregorc40290e2009-03-09 23:48:35 +00001100 : TemplateArgument(reinterpret_cast<Expr *>(Args[Arg])));
1101 }
1102}
1103
Douglas Gregordc572a32009-03-30 22:58:21 +00001104QualType Sema::CheckTemplateIdType(TemplateName Name,
1105 SourceLocation TemplateLoc,
1106 SourceLocation LAngleLoc,
1107 const TemplateArgument *TemplateArgs,
1108 unsigned NumTemplateArgs,
1109 SourceLocation RAngleLoc) {
1110 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregorb67535d2009-03-31 00:43:58 +00001111 if (!Template) {
1112 // The template name does not resolve to a template, so we just
1113 // build a dependent template-id type.
Douglas Gregorb67535d2009-03-31 00:43:58 +00001114 return Context.getTemplateSpecializationType(Name, TemplateArgs,
Douglas Gregora8e02e72009-07-28 23:00:59 +00001115 NumTemplateArgs);
Douglas Gregorb67535d2009-03-31 00:43:58 +00001116 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001117
Douglas Gregorc40290e2009-03-09 23:48:35 +00001118 // Check that the template argument list is well-formed for this
1119 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001120 TemplateArgumentListBuilder Converted(Template->getTemplateParameters(),
1121 NumTemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00001122 if (CheckTemplateArgumentList(Template, TemplateLoc, LAngleLoc,
Douglas Gregorc40290e2009-03-09 23:48:35 +00001123 TemplateArgs, NumTemplateArgs, RAngleLoc,
Douglas Gregore3f1f352009-07-01 00:28:38 +00001124 false, Converted))
Douglas Gregorc40290e2009-03-09 23:48:35 +00001125 return QualType();
1126
Mike Stump11289f42009-09-09 15:08:12 +00001127 assert((Converted.structuredSize() ==
Douglas Gregordc572a32009-03-30 22:58:21 +00001128 Template->getTemplateParameters()->size()) &&
Douglas Gregorc40290e2009-03-09 23:48:35 +00001129 "Converted template argument list is too short!");
1130
1131 QualType CanonType;
1132
Douglas Gregordc572a32009-03-30 22:58:21 +00001133 if (TemplateSpecializationType::anyDependentTemplateArguments(
Douglas Gregorc40290e2009-03-09 23:48:35 +00001134 TemplateArgs,
1135 NumTemplateArgs)) {
1136 // This class template specialization is a dependent
1137 // type. Therefore, its canonical type is another class template
1138 // specialization type that contains all of the converted
1139 // arguments in canonical form. This ensures that, e.g., A<T> and
1140 // A<T, T> have identical types when A is declared as:
1141 //
1142 // template<typename T, typename U = T> struct A;
Douglas Gregor6bc50582009-05-07 06:41:52 +00001143 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
Mike Stump11289f42009-09-09 15:08:12 +00001144 CanonType = Context.getTemplateSpecializationType(CanonName,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001145 Converted.getFlatArguments(),
1146 Converted.flatSize());
Mike Stump11289f42009-09-09 15:08:12 +00001147
Douglas Gregora8e02e72009-07-28 23:00:59 +00001148 // FIXME: CanonType is not actually the canonical type, and unfortunately
1149 // it is a TemplateTypeSpecializationType that we will never use again.
1150 // In the future, we need to teach getTemplateSpecializationType to only
1151 // build the canonical type and return that to us.
1152 CanonType = Context.getCanonicalType(CanonType);
Mike Stump11289f42009-09-09 15:08:12 +00001153 } else if (ClassTemplateDecl *ClassTemplate
Douglas Gregordc572a32009-03-30 22:58:21 +00001154 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00001155 // Find the class template specialization declaration that
1156 // corresponds to these arguments.
1157 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00001158 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001159 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00001160 Converted.flatSize(),
1161 Context);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001162 void *InsertPos = 0;
1163 ClassTemplateSpecializationDecl *Decl
1164 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
1165 if (!Decl) {
1166 // This is the first time we have referenced this class template
1167 // specialization. Create the canonical declaration and add it to
1168 // the set of specializations.
Mike Stump11289f42009-09-09 15:08:12 +00001169 Decl = ClassTemplateSpecializationDecl::Create(Context,
Anders Carlsson8aa89d42009-06-05 03:43:12 +00001170 ClassTemplate->getDeclContext(),
John McCall1806c272009-09-11 07:25:08 +00001171 ClassTemplate->getLocation(),
Anders Carlsson8aa89d42009-06-05 03:43:12 +00001172 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001173 Converted, 0);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001174 ClassTemplate->getSpecializations().InsertNode(Decl, InsertPos);
1175 Decl->setLexicalDeclContext(CurContext);
1176 }
1177
1178 CanonType = Context.getTypeDeclType(Decl);
1179 }
Mike Stump11289f42009-09-09 15:08:12 +00001180
Douglas Gregorc40290e2009-03-09 23:48:35 +00001181 // Build the fully-sugared type for this class template
1182 // specialization, which refers back to the class template
1183 // specialization we created or found.
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00001184 //FIXME: Preserve type source info.
Douglas Gregordc572a32009-03-30 22:58:21 +00001185 return Context.getTemplateSpecializationType(Name, TemplateArgs,
1186 NumTemplateArgs, CanonType);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001187}
1188
Douglas Gregor67a65642009-02-17 23:15:12 +00001189Action::TypeResult
Douglas Gregordc572a32009-03-30 22:58:21 +00001190Sema::ActOnTemplateIdType(TemplateTy TemplateD, SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00001191 SourceLocation LAngleLoc,
Douglas Gregordc572a32009-03-30 22:58:21 +00001192 ASTTemplateArgsPtr TemplateArgsIn,
1193 SourceLocation *TemplateArgLocs,
John McCalld8fe9af2009-09-08 17:47:29 +00001194 SourceLocation RAngleLoc) {
Douglas Gregordc572a32009-03-30 22:58:21 +00001195 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Douglas Gregor8bf42052009-02-09 18:46:07 +00001196
Douglas Gregorc40290e2009-03-09 23:48:35 +00001197 // Translate the parser's template argument list in our AST format.
1198 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
1199 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
Douglas Gregord32e0282009-02-09 23:23:08 +00001200
Douglas Gregordc572a32009-03-30 22:58:21 +00001201 QualType Result = CheckTemplateIdType(Template, TemplateLoc, LAngleLoc,
Jay Foad7d0479f2009-05-21 09:52:38 +00001202 TemplateArgs.data(),
1203 TemplateArgs.size(),
Douglas Gregordc572a32009-03-30 22:58:21 +00001204 RAngleLoc);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001205 TemplateArgsIn.release();
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00001206
1207 if (Result.isNull())
1208 return true;
1209
John McCalld8fe9af2009-09-08 17:47:29 +00001210 return Result.getAsOpaquePtr();
1211}
John McCall06f6fe8d2009-09-04 01:14:41 +00001212
John McCalld8fe9af2009-09-08 17:47:29 +00001213Sema::TypeResult Sema::ActOnTagTemplateIdType(TypeResult TypeResult,
1214 TagUseKind TUK,
1215 DeclSpec::TST TagSpec,
1216 SourceLocation TagLoc) {
1217 if (TypeResult.isInvalid())
1218 return Sema::TypeResult();
John McCall06f6fe8d2009-09-04 01:14:41 +00001219
John McCalld8fe9af2009-09-08 17:47:29 +00001220 QualType Type = QualType::getFromOpaquePtr(TypeResult.get());
John McCall06f6fe8d2009-09-04 01:14:41 +00001221
John McCalld8fe9af2009-09-08 17:47:29 +00001222 // Verify the tag specifier.
1223 TagDecl::TagKind TagKind = TagDecl::getTagKindForTypeSpec(TagSpec);
Mike Stump11289f42009-09-09 15:08:12 +00001224
John McCalld8fe9af2009-09-08 17:47:29 +00001225 if (const RecordType *RT = Type->getAs<RecordType>()) {
1226 RecordDecl *D = RT->getDecl();
1227
1228 IdentifierInfo *Id = D->getIdentifier();
1229 assert(Id && "templated class must have an identifier");
1230
1231 if (!isAcceptableTagRedeclaration(D, TagKind, TagLoc, *Id)) {
1232 Diag(TagLoc, diag::err_use_with_wrong_tag)
John McCall7f41d982009-09-11 04:59:25 +00001233 << Type
John McCalld8fe9af2009-09-08 17:47:29 +00001234 << CodeModificationHint::CreateReplacement(SourceRange(TagLoc),
1235 D->getKindName());
John McCall7f41d982009-09-11 04:59:25 +00001236 Diag(D->getLocation(), diag::note_previous_use);
John McCall06f6fe8d2009-09-04 01:14:41 +00001237 }
1238 }
1239
John McCalld8fe9af2009-09-08 17:47:29 +00001240 QualType ElabType = Context.getElaboratedType(Type, TagKind);
1241
1242 return ElabType.getAsOpaquePtr();
Douglas Gregor8bf42052009-02-09 18:46:07 +00001243}
1244
Douglas Gregora727cb92009-06-30 22:34:41 +00001245Sema::OwningExprResult Sema::BuildTemplateIdExpr(TemplateName Template,
1246 SourceLocation TemplateNameLoc,
1247 SourceLocation LAngleLoc,
1248 const TemplateArgument *TemplateArgs,
1249 unsigned NumTemplateArgs,
1250 SourceLocation RAngleLoc) {
1251 // FIXME: Can we do any checking at this point? I guess we could check the
1252 // template arguments that we have against the template name, if the template
Mike Stump11289f42009-09-09 15:08:12 +00001253 // name refers to a single template. That's not a terribly common case,
Douglas Gregora727cb92009-06-30 22:34:41 +00001254 // though.
Mike Stump11289f42009-09-09 15:08:12 +00001255 return Owned(TemplateIdRefExpr::Create(Context,
Douglas Gregora727cb92009-06-30 22:34:41 +00001256 /*FIXME: New type?*/Context.OverloadTy,
1257 /*FIXME: Necessary?*/0,
1258 /*FIXME: Necessary?*/SourceRange(),
1259 Template, TemplateNameLoc, LAngleLoc,
Mike Stump11289f42009-09-09 15:08:12 +00001260 TemplateArgs,
Douglas Gregora727cb92009-06-30 22:34:41 +00001261 NumTemplateArgs, RAngleLoc));
1262}
1263
1264Sema::OwningExprResult Sema::ActOnTemplateIdExpr(TemplateTy TemplateD,
1265 SourceLocation TemplateNameLoc,
1266 SourceLocation LAngleLoc,
1267 ASTTemplateArgsPtr TemplateArgsIn,
1268 SourceLocation *TemplateArgLocs,
1269 SourceLocation RAngleLoc) {
1270 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Mike Stump11289f42009-09-09 15:08:12 +00001271
Douglas Gregora727cb92009-06-30 22:34:41 +00001272 // Translate the parser's template argument list in our AST format.
1273 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
1274 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
Douglas Gregorb77af8f2009-07-22 20:55:49 +00001275 TemplateArgsIn.release();
Mike Stump11289f42009-09-09 15:08:12 +00001276
Douglas Gregora727cb92009-06-30 22:34:41 +00001277 return BuildTemplateIdExpr(Template, TemplateNameLoc, LAngleLoc,
1278 TemplateArgs.data(), TemplateArgs.size(),
1279 RAngleLoc);
1280}
1281
Douglas Gregor84f14dd2009-09-01 00:37:14 +00001282Sema::OwningExprResult
1283Sema::ActOnMemberTemplateIdReferenceExpr(Scope *S, ExprArg Base,
1284 SourceLocation OpLoc,
1285 tok::TokenKind OpKind,
1286 const CXXScopeSpec &SS,
1287 TemplateTy TemplateD,
1288 SourceLocation TemplateNameLoc,
1289 SourceLocation LAngleLoc,
1290 ASTTemplateArgsPtr TemplateArgsIn,
1291 SourceLocation *TemplateArgLocs,
1292 SourceLocation RAngleLoc) {
1293 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Mike Stump11289f42009-09-09 15:08:12 +00001294
Douglas Gregor84f14dd2009-09-01 00:37:14 +00001295 // FIXME: We're going to end up looking up the template based on its name,
1296 // twice!
1297 DeclarationName Name;
1298 if (TemplateDecl *ActualTemplate = Template.getAsTemplateDecl())
1299 Name = ActualTemplate->getDeclName();
1300 else if (OverloadedFunctionDecl *Ovl = Template.getAsOverloadedFunctionDecl())
1301 Name = Ovl->getDeclName();
1302 else
Douglas Gregor308047d2009-09-09 00:23:06 +00001303 Name = Template.getAsDependentTemplateName()->getName();
Mike Stump11289f42009-09-09 15:08:12 +00001304
Douglas Gregor84f14dd2009-09-01 00:37:14 +00001305 // Translate the parser's template argument list in our AST format.
1306 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
1307 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
1308 TemplateArgsIn.release();
Mike Stump11289f42009-09-09 15:08:12 +00001309
Douglas Gregor84f14dd2009-09-01 00:37:14 +00001310 // Do we have the save the actual template name? We might need it...
1311 return BuildMemberReferenceExpr(S, move(Base), OpLoc, OpKind, TemplateNameLoc,
1312 Name, true, LAngleLoc,
1313 TemplateArgs.data(), TemplateArgs.size(),
Mike Stump11289f42009-09-09 15:08:12 +00001314 RAngleLoc, DeclPtrTy(), &SS);
Douglas Gregor84f14dd2009-09-01 00:37:14 +00001315}
1316
Douglas Gregorb67535d2009-03-31 00:43:58 +00001317/// \brief Form a dependent template name.
1318///
1319/// This action forms a dependent template name given the template
1320/// name and its (presumably dependent) scope specifier. For
1321/// example, given "MetaFun::template apply", the scope specifier \p
1322/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
1323/// of the "template" keyword, and "apply" is the \p Name.
Mike Stump11289f42009-09-09 15:08:12 +00001324Sema::TemplateTy
Douglas Gregorb67535d2009-03-31 00:43:58 +00001325Sema::ActOnDependentTemplateName(SourceLocation TemplateKWLoc,
1326 const IdentifierInfo &Name,
1327 SourceLocation NameLoc,
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001328 const CXXScopeSpec &SS,
1329 TypeTy *ObjectType) {
Mike Stump11289f42009-09-09 15:08:12 +00001330 if ((ObjectType &&
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001331 computeDeclContext(QualType::getFromOpaquePtr(ObjectType))) ||
1332 (SS.isSet() && computeDeclContext(SS, false))) {
Douglas Gregorb67535d2009-03-31 00:43:58 +00001333 // C++0x [temp.names]p5:
1334 // If a name prefixed by the keyword template is not the name of
1335 // a template, the program is ill-formed. [Note: the keyword
1336 // template may not be applied to non-template members of class
1337 // templates. -end note ] [ Note: as is the case with the
1338 // typename prefix, the template prefix is allowed in cases
1339 // where it is not strictly necessary; i.e., when the
1340 // nested-name-specifier or the expression on the left of the ->
1341 // or . is not dependent on a template-parameter, or the use
1342 // does not appear in the scope of a template. -end note]
1343 //
1344 // Note: C++03 was more strict here, because it banned the use of
1345 // the "template" keyword prior to a template-name that was not a
1346 // dependent name. C++ DR468 relaxed this requirement (the
1347 // "template" keyword is now permitted). We follow the C++0x
1348 // rules, even in C++03 mode, retroactively applying the DR.
1349 TemplateTy Template;
Mike Stump11289f42009-09-09 15:08:12 +00001350 TemplateNameKind TNK = isTemplateName(0, Name, NameLoc, &SS, ObjectType,
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001351 false, Template);
Douglas Gregorb67535d2009-03-31 00:43:58 +00001352 if (TNK == TNK_Non_template) {
1353 Diag(NameLoc, diag::err_template_kw_refers_to_non_template)
1354 << &Name;
1355 return TemplateTy();
1356 }
1357
1358 return Template;
1359 }
1360
Mike Stump11289f42009-09-09 15:08:12 +00001361 NestedNameSpecifier *Qualifier
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001362 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Douglas Gregorb67535d2009-03-31 00:43:58 +00001363 return TemplateTy::make(Context.getDependentTemplateName(Qualifier, &Name));
1364}
1365
Mike Stump11289f42009-09-09 15:08:12 +00001366bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001367 const TemplateArgument &Arg,
1368 TemplateArgumentListBuilder &Converted) {
1369 // Check template type parameter.
1370 if (Arg.getKind() != TemplateArgument::Type) {
1371 // C++ [temp.arg.type]p1:
1372 // A template-argument for a template-parameter which is a
1373 // type shall be a type-id.
1374
1375 // We have a template type parameter but the template argument
1376 // is not a type.
1377 Diag(Arg.getLocation(), diag::err_template_arg_must_be_type);
1378 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00001379
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001380 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001381 }
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001382
1383 if (CheckTemplateArgument(Param, Arg.getAsType(), Arg.getLocation()))
1384 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001385
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001386 // Add the converted template type argument.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001387 Converted.Append(
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001388 TemplateArgument(Arg.getLocation(),
1389 Context.getCanonicalType(Arg.getAsType())));
1390 return false;
1391}
1392
Douglas Gregord32e0282009-02-09 23:23:08 +00001393/// \brief Check that the given template argument list is well-formed
1394/// for specializing the given template.
1395bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
1396 SourceLocation TemplateLoc,
1397 SourceLocation LAngleLoc,
Douglas Gregorc40290e2009-03-09 23:48:35 +00001398 const TemplateArgument *TemplateArgs,
1399 unsigned NumTemplateArgs,
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001400 SourceLocation RAngleLoc,
Douglas Gregore3f1f352009-07-01 00:28:38 +00001401 bool PartialTemplateArgs,
Anders Carlsson8aa89d42009-06-05 03:43:12 +00001402 TemplateArgumentListBuilder &Converted) {
Douglas Gregord32e0282009-02-09 23:23:08 +00001403 TemplateParameterList *Params = Template->getTemplateParameters();
1404 unsigned NumParams = Params->size();
Douglas Gregorc40290e2009-03-09 23:48:35 +00001405 unsigned NumArgs = NumTemplateArgs;
Douglas Gregord32e0282009-02-09 23:23:08 +00001406 bool Invalid = false;
1407
Mike Stump11289f42009-09-09 15:08:12 +00001408 bool HasParameterPack =
Anders Carlsson15201f12009-06-13 02:08:00 +00001409 NumParams > 0 && Params->getParam(NumParams - 1)->isTemplateParameterPack();
Mike Stump11289f42009-09-09 15:08:12 +00001410
Anders Carlsson15201f12009-06-13 02:08:00 +00001411 if ((NumArgs > NumParams && !HasParameterPack) ||
Douglas Gregore3f1f352009-07-01 00:28:38 +00001412 (NumArgs < Params->getMinRequiredArguments() &&
1413 !PartialTemplateArgs)) {
Douglas Gregord32e0282009-02-09 23:23:08 +00001414 // FIXME: point at either the first arg beyond what we can handle,
1415 // or the '>', depending on whether we have too many or too few
1416 // arguments.
1417 SourceRange Range;
1418 if (NumArgs > NumParams)
Douglas Gregorc40290e2009-03-09 23:48:35 +00001419 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
Douglas Gregord32e0282009-02-09 23:23:08 +00001420 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
1421 << (NumArgs > NumParams)
1422 << (isa<ClassTemplateDecl>(Template)? 0 :
1423 isa<FunctionTemplateDecl>(Template)? 1 :
1424 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
1425 << Template << Range;
Douglas Gregorf8f86832009-02-11 18:16:40 +00001426 Diag(Template->getLocation(), diag::note_template_decl_here)
1427 << Params->getSourceRange();
Douglas Gregord32e0282009-02-09 23:23:08 +00001428 Invalid = true;
1429 }
Mike Stump11289f42009-09-09 15:08:12 +00001430
1431 // C++ [temp.arg]p1:
Douglas Gregord32e0282009-02-09 23:23:08 +00001432 // [...] The type and form of each template-argument specified in
1433 // a template-id shall match the type and form specified for the
1434 // corresponding parameter declared by the template in its
1435 // template-parameter-list.
1436 unsigned ArgIdx = 0;
1437 for (TemplateParameterList::iterator Param = Params->begin(),
1438 ParamEnd = Params->end();
1439 Param != ParamEnd; ++Param, ++ArgIdx) {
Douglas Gregore3f1f352009-07-01 00:28:38 +00001440 if (ArgIdx > NumArgs && PartialTemplateArgs)
1441 break;
Mike Stump11289f42009-09-09 15:08:12 +00001442
Douglas Gregord32e0282009-02-09 23:23:08 +00001443 // Decode the template argument
Douglas Gregorc40290e2009-03-09 23:48:35 +00001444 TemplateArgument Arg;
Douglas Gregord32e0282009-02-09 23:23:08 +00001445 if (ArgIdx >= NumArgs) {
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001446 // Retrieve the default template argument from the template
1447 // parameter.
1448 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
Anders Carlsson15201f12009-06-13 02:08:00 +00001449 if (TTP->isParameterPack()) {
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001450 // We have an empty argument pack.
1451 Converted.BeginPack();
1452 Converted.EndPack();
Anders Carlsson15201f12009-06-13 02:08:00 +00001453 break;
1454 }
Mike Stump11289f42009-09-09 15:08:12 +00001455
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001456 if (!TTP->hasDefaultArgument())
1457 break;
1458
Douglas Gregorc40290e2009-03-09 23:48:35 +00001459 QualType ArgType = TTP->getDefaultArgument();
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001460
1461 // If the argument type is dependent, instantiate it now based
1462 // on the previously-computed template arguments.
Douglas Gregor79cf6032009-03-10 20:44:00 +00001463 if (ArgType->isDependentType()) {
Mike Stump11289f42009-09-09 15:08:12 +00001464 InstantiatingTemplate Inst(*this, TemplateLoc,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001465 Template, Converted.getFlatArguments(),
Anders Carlsson8aa89d42009-06-05 03:43:12 +00001466 Converted.flatSize(),
Douglas Gregor79cf6032009-03-10 20:44:00 +00001467 SourceRange(TemplateLoc, RAngleLoc));
Douglas Gregord002c7b2009-05-11 23:53:27 +00001468
Anders Carlssonc8e71132009-06-05 04:47:51 +00001469 TemplateArgumentList TemplateArgs(Context, Converted,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001470 /*TakeArgs=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00001471 ArgType = SubstType(ArgType,
Douglas Gregor01afeef2009-08-28 20:31:08 +00001472 MultiLevelTemplateArgumentList(TemplateArgs),
John McCall76d824f2009-08-25 22:02:44 +00001473 TTP->getDefaultArgumentLoc(),
1474 TTP->getDeclName());
Douglas Gregor79cf6032009-03-10 20:44:00 +00001475 }
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001476
1477 if (ArgType.isNull())
Douglas Gregor17c0d7b2009-02-28 00:25:32 +00001478 return true;
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001479
Douglas Gregorc40290e2009-03-09 23:48:35 +00001480 Arg = TemplateArgument(TTP->getLocation(), ArgType);
Mike Stump11289f42009-09-09 15:08:12 +00001481 } else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001482 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
1483 if (!NTTP->hasDefaultArgument())
1484 break;
1485
Mike Stump11289f42009-09-09 15:08:12 +00001486 InstantiatingTemplate Inst(*this, TemplateLoc,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001487 Template, Converted.getFlatArguments(),
Anders Carlsson40ed3442009-06-11 16:06:49 +00001488 Converted.flatSize(),
1489 SourceRange(TemplateLoc, RAngleLoc));
Mike Stump11289f42009-09-09 15:08:12 +00001490
Anders Carlsson40ed3442009-06-11 16:06:49 +00001491 TemplateArgumentList TemplateArgs(Context, Converted,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001492 /*TakeArgs=*/false);
Anders Carlsson40ed3442009-06-11 16:06:49 +00001493
Mike Stump11289f42009-09-09 15:08:12 +00001494 Sema::OwningExprResult E
1495 = SubstExpr(NTTP->getDefaultArgument(),
Douglas Gregor01afeef2009-08-28 20:31:08 +00001496 MultiLevelTemplateArgumentList(TemplateArgs));
Anders Carlsson40ed3442009-06-11 16:06:49 +00001497 if (E.isInvalid())
1498 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001499
Anders Carlsson40ed3442009-06-11 16:06:49 +00001500 Arg = TemplateArgument(E.takeAs<Expr>());
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001501 } else {
Mike Stump11289f42009-09-09 15:08:12 +00001502 TemplateTemplateParmDecl *TempParm
1503 = cast<TemplateTemplateParmDecl>(*Param);
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001504
1505 if (!TempParm->hasDefaultArgument())
1506 break;
1507
John McCall76d824f2009-08-25 22:02:44 +00001508 // FIXME: Subst default argument
Douglas Gregorc40290e2009-03-09 23:48:35 +00001509 Arg = TemplateArgument(TempParm->getDefaultArgument());
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001510 }
1511 } else {
1512 // Retrieve the template argument produced by the user.
Douglas Gregorc40290e2009-03-09 23:48:35 +00001513 Arg = TemplateArgs[ArgIdx];
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001514 }
1515
Douglas Gregord32e0282009-02-09 23:23:08 +00001516
1517 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
Anders Carlsson15201f12009-06-13 02:08:00 +00001518 if (TTP->isParameterPack()) {
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001519 Converted.BeginPack();
Anders Carlsson15201f12009-06-13 02:08:00 +00001520 // Check all the remaining arguments (if any).
1521 for (; ArgIdx < NumArgs; ++ArgIdx) {
1522 if (CheckTemplateTypeArgument(TTP, TemplateArgs[ArgIdx], Converted))
1523 Invalid = true;
1524 }
Mike Stump11289f42009-09-09 15:08:12 +00001525
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001526 Converted.EndPack();
Anders Carlsson15201f12009-06-13 02:08:00 +00001527 } else {
1528 if (CheckTemplateTypeArgument(TTP, Arg, Converted))
1529 Invalid = true;
1530 }
Mike Stump11289f42009-09-09 15:08:12 +00001531 } else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregord32e0282009-02-09 23:23:08 +00001532 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
1533 // Check non-type template parameters.
Douglas Gregor463421d2009-03-03 04:44:36 +00001534
John McCall76d824f2009-08-25 22:02:44 +00001535 // Do substitution on the type of the non-type template parameter
1536 // with the template arguments we've seen thus far.
Douglas Gregor463421d2009-03-03 04:44:36 +00001537 QualType NTTPType = NTTP->getType();
1538 if (NTTPType->isDependentType()) {
John McCall76d824f2009-08-25 22:02:44 +00001539 // Do substitution on the type of the non-type template parameter.
Mike Stump11289f42009-09-09 15:08:12 +00001540 InstantiatingTemplate Inst(*this, TemplateLoc,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001541 Template, Converted.getFlatArguments(),
Anders Carlsson8aa89d42009-06-05 03:43:12 +00001542 Converted.flatSize(),
Douglas Gregor79cf6032009-03-10 20:44:00 +00001543 SourceRange(TemplateLoc, RAngleLoc));
1544
Anders Carlssonc8e71132009-06-05 04:47:51 +00001545 TemplateArgumentList TemplateArgs(Context, Converted,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001546 /*TakeArgs=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00001547 NTTPType = SubstType(NTTPType,
Douglas Gregor39cacdb2009-08-28 20:50:45 +00001548 MultiLevelTemplateArgumentList(TemplateArgs),
John McCall76d824f2009-08-25 22:02:44 +00001549 NTTP->getLocation(),
1550 NTTP->getDeclName());
Douglas Gregor463421d2009-03-03 04:44:36 +00001551 // If that worked, check the non-type template parameter type
1552 // for validity.
1553 if (!NTTPType.isNull())
Mike Stump11289f42009-09-09 15:08:12 +00001554 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
Douglas Gregor463421d2009-03-03 04:44:36 +00001555 NTTP->getLocation());
Douglas Gregor463421d2009-03-03 04:44:36 +00001556 if (NTTPType.isNull()) {
1557 Invalid = true;
1558 break;
1559 }
1560 }
1561
Douglas Gregorc40290e2009-03-09 23:48:35 +00001562 switch (Arg.getKind()) {
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001563 case TemplateArgument::Null:
1564 assert(false && "Should never see a NULL template argument here");
1565 break;
Mike Stump11289f42009-09-09 15:08:12 +00001566
Douglas Gregorc40290e2009-03-09 23:48:35 +00001567 case TemplateArgument::Expression: {
1568 Expr *E = Arg.getAsExpr();
Douglas Gregor74eba0b2009-06-11 18:10:32 +00001569 TemplateArgument Result;
1570 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
Douglas Gregord32e0282009-02-09 23:23:08 +00001571 Invalid = true;
Douglas Gregor74eba0b2009-06-11 18:10:32 +00001572 else
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001573 Converted.Append(Result);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001574 break;
Douglas Gregord32e0282009-02-09 23:23:08 +00001575 }
1576
Douglas Gregorc40290e2009-03-09 23:48:35 +00001577 case TemplateArgument::Declaration:
1578 case TemplateArgument::Integral:
1579 // We've already checked this template argument, so just copy
1580 // it to the list of converted arguments.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001581 Converted.Append(Arg);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001582 break;
Douglas Gregord32e0282009-02-09 23:23:08 +00001583
Douglas Gregorc40290e2009-03-09 23:48:35 +00001584 case TemplateArgument::Type:
1585 // We have a non-type template parameter but the template
1586 // argument is a type.
Mike Stump11289f42009-09-09 15:08:12 +00001587
Douglas Gregorc40290e2009-03-09 23:48:35 +00001588 // C++ [temp.arg]p2:
1589 // In a template-argument, an ambiguity between a type-id and
1590 // an expression is resolved to a type-id, regardless of the
1591 // form of the corresponding template-parameter.
1592 //
1593 // We warn specifically about this case, since it can be rather
1594 // confusing for users.
1595 if (Arg.getAsType()->isFunctionType())
1596 Diag(Arg.getLocation(), diag::err_template_arg_nontype_ambig)
1597 << Arg.getAsType();
1598 else
1599 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr);
1600 Diag((*Param)->getLocation(), diag::note_template_param_here);
1601 Invalid = true;
Anders Carlssonbc343912009-06-15 17:04:53 +00001602 break;
Mike Stump11289f42009-09-09 15:08:12 +00001603
Anders Carlssonbc343912009-06-15 17:04:53 +00001604 case TemplateArgument::Pack:
1605 assert(0 && "FIXME: Implement!");
1606 break;
Douglas Gregorc40290e2009-03-09 23:48:35 +00001607 }
Mike Stump11289f42009-09-09 15:08:12 +00001608 } else {
Douglas Gregord32e0282009-02-09 23:23:08 +00001609 // Check template template parameters.
Mike Stump11289f42009-09-09 15:08:12 +00001610 TemplateTemplateParmDecl *TempParm
Douglas Gregord32e0282009-02-09 23:23:08 +00001611 = cast<TemplateTemplateParmDecl>(*Param);
Mike Stump11289f42009-09-09 15:08:12 +00001612
Douglas Gregorc40290e2009-03-09 23:48:35 +00001613 switch (Arg.getKind()) {
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001614 case TemplateArgument::Null:
1615 assert(false && "Should never see a NULL template argument here");
1616 break;
Mike Stump11289f42009-09-09 15:08:12 +00001617
Douglas Gregorc40290e2009-03-09 23:48:35 +00001618 case TemplateArgument::Expression: {
1619 Expr *ArgExpr = Arg.getAsExpr();
1620 if (ArgExpr && isa<DeclRefExpr>(ArgExpr) &&
1621 isa<TemplateDecl>(cast<DeclRefExpr>(ArgExpr)->getDecl())) {
1622 if (CheckTemplateArgument(TempParm, cast<DeclRefExpr>(ArgExpr)))
1623 Invalid = true;
Mike Stump11289f42009-09-09 15:08:12 +00001624
Douglas Gregorc40290e2009-03-09 23:48:35 +00001625 // Add the converted template argument.
Mike Stump11289f42009-09-09 15:08:12 +00001626 Decl *D
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00001627 = cast<DeclRefExpr>(ArgExpr)->getDecl()->getCanonicalDecl();
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001628 Converted.Append(TemplateArgument(Arg.getLocation(), D));
Douglas Gregorc40290e2009-03-09 23:48:35 +00001629 continue;
1630 }
1631 }
1632 // fall through
Mike Stump11289f42009-09-09 15:08:12 +00001633
Douglas Gregorc40290e2009-03-09 23:48:35 +00001634 case TemplateArgument::Type: {
1635 // We have a template template parameter but the template
1636 // argument does not refer to a template.
1637 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
1638 Invalid = true;
1639 break;
Douglas Gregord32e0282009-02-09 23:23:08 +00001640 }
1641
Douglas Gregorc40290e2009-03-09 23:48:35 +00001642 case TemplateArgument::Declaration:
1643 // We've already checked this template argument, so just copy
1644 // it to the list of converted arguments.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001645 Converted.Append(Arg);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001646 break;
Mike Stump11289f42009-09-09 15:08:12 +00001647
Douglas Gregorc40290e2009-03-09 23:48:35 +00001648 case TemplateArgument::Integral:
1649 assert(false && "Integral argument with template template parameter");
1650 break;
Mike Stump11289f42009-09-09 15:08:12 +00001651
Anders Carlssonbc343912009-06-15 17:04:53 +00001652 case TemplateArgument::Pack:
1653 assert(0 && "FIXME: Implement!");
1654 break;
Douglas Gregorc40290e2009-03-09 23:48:35 +00001655 }
Douglas Gregord32e0282009-02-09 23:23:08 +00001656 }
1657 }
1658
1659 return Invalid;
1660}
1661
1662/// \brief Check a template argument against its corresponding
1663/// template type parameter.
1664///
1665/// This routine implements the semantics of C++ [temp.arg.type]. It
1666/// returns true if an error occurred, and false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001667bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
Douglas Gregord32e0282009-02-09 23:23:08 +00001668 QualType Arg, SourceLocation ArgLoc) {
1669 // C++ [temp.arg.type]p2:
1670 // A local type, a type with no linkage, an unnamed type or a type
1671 // compounded from any of these types shall not be used as a
1672 // template-argument for a template type-parameter.
1673 //
1674 // FIXME: Perform the recursive and no-linkage type checks.
1675 const TagType *Tag = 0;
John McCall9dd450b2009-09-21 23:43:11 +00001676 if (const EnumType *EnumT = Arg->getAs<EnumType>())
Douglas Gregord32e0282009-02-09 23:23:08 +00001677 Tag = EnumT;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001678 else if (const RecordType *RecordT = Arg->getAs<RecordType>())
Douglas Gregord32e0282009-02-09 23:23:08 +00001679 Tag = RecordT;
1680 if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod())
1681 return Diag(ArgLoc, diag::err_template_arg_local_type)
1682 << QualType(Tag, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001683 else if (Tag && !Tag->getDecl()->getDeclName() &&
Douglas Gregor65b2c4c2009-03-10 18:33:27 +00001684 !Tag->getDecl()->getTypedefForAnonDecl()) {
Douglas Gregord32e0282009-02-09 23:23:08 +00001685 Diag(ArgLoc, diag::err_template_arg_unnamed_type);
1686 Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here);
1687 return true;
1688 }
1689
1690 return false;
1691}
1692
Douglas Gregorccb07762009-02-11 19:52:55 +00001693/// \brief Checks whether the given template argument is the address
1694/// of an object or function according to C++ [temp.arg.nontype]p1.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001695bool Sema::CheckTemplateArgumentAddressOfObjectOrFunction(Expr *Arg,
1696 NamedDecl *&Entity) {
Douglas Gregorccb07762009-02-11 19:52:55 +00001697 bool Invalid = false;
1698
1699 // See through any implicit casts we added to fix the type.
1700 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
1701 Arg = Cast->getSubExpr();
1702
Sebastian Redl576fd422009-05-10 18:38:11 +00001703 // C++0x allows nullptr, and there's no further checking to be done for that.
1704 if (Arg->getType()->isNullPtrType())
1705 return false;
1706
Douglas Gregorccb07762009-02-11 19:52:55 +00001707 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00001708 //
Douglas Gregorccb07762009-02-11 19:52:55 +00001709 // A template-argument for a non-type, non-template
1710 // template-parameter shall be one of: [...]
1711 //
1712 // -- the address of an object or function with external
1713 // linkage, including function templates and function
1714 // template-ids but excluding non-static class members,
1715 // expressed as & id-expression where the & is optional if
1716 // the name refers to a function or array, or if the
1717 // corresponding template-parameter is a reference; or
1718 DeclRefExpr *DRE = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001719
Douglas Gregorccb07762009-02-11 19:52:55 +00001720 // Ignore (and complain about) any excess parentheses.
1721 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
1722 if (!Invalid) {
Mike Stump11289f42009-09-09 15:08:12 +00001723 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00001724 diag::err_template_arg_extra_parens)
1725 << Arg->getSourceRange();
1726 Invalid = true;
1727 }
1728
1729 Arg = Parens->getSubExpr();
1730 }
1731
1732 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
1733 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
1734 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
1735 } else
1736 DRE = dyn_cast<DeclRefExpr>(Arg);
1737
1738 if (!DRE || !isa<ValueDecl>(DRE->getDecl()))
Mike Stump11289f42009-09-09 15:08:12 +00001739 return Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00001740 diag::err_template_arg_not_object_or_func_form)
1741 << Arg->getSourceRange();
1742
1743 // Cannot refer to non-static data members
1744 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl()))
1745 return Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
1746 << Field << Arg->getSourceRange();
1747
1748 // Cannot refer to non-static member functions
1749 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
1750 if (!Method->isStatic())
Mike Stump11289f42009-09-09 15:08:12 +00001751 return Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00001752 diag::err_template_arg_method)
1753 << Method << Arg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00001754
Douglas Gregorccb07762009-02-11 19:52:55 +00001755 // Functions must have external linkage.
1756 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
1757 if (Func->getStorageClass() == FunctionDecl::Static) {
Mike Stump11289f42009-09-09 15:08:12 +00001758 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00001759 diag::err_template_arg_function_not_extern)
1760 << Func << Arg->getSourceRange();
1761 Diag(Func->getLocation(), diag::note_template_arg_internal_object)
1762 << true;
1763 return true;
1764 }
1765
1766 // Okay: we've named a function with external linkage.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001767 Entity = Func;
Douglas Gregorccb07762009-02-11 19:52:55 +00001768 return Invalid;
1769 }
1770
1771 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
1772 if (!Var->hasGlobalStorage()) {
Mike Stump11289f42009-09-09 15:08:12 +00001773 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00001774 diag::err_template_arg_object_not_extern)
1775 << Var << Arg->getSourceRange();
1776 Diag(Var->getLocation(), diag::note_template_arg_internal_object)
1777 << true;
1778 return true;
1779 }
1780
1781 // Okay: we've named an object with external linkage
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001782 Entity = Var;
Douglas Gregorccb07762009-02-11 19:52:55 +00001783 return Invalid;
1784 }
Mike Stump11289f42009-09-09 15:08:12 +00001785
Douglas Gregorccb07762009-02-11 19:52:55 +00001786 // We found something else, but we don't know specifically what it is.
Mike Stump11289f42009-09-09 15:08:12 +00001787 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00001788 diag::err_template_arg_not_object_or_func)
1789 << Arg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00001790 Diag(DRE->getDecl()->getLocation(),
Douglas Gregorccb07762009-02-11 19:52:55 +00001791 diag::note_template_arg_refers_here);
1792 return true;
1793}
1794
1795/// \brief Checks whether the given template argument is a pointer to
1796/// member constant according to C++ [temp.arg.nontype]p1.
Mike Stump11289f42009-09-09 15:08:12 +00001797bool
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001798Sema::CheckTemplateArgumentPointerToMember(Expr *Arg, NamedDecl *&Member) {
Douglas Gregorccb07762009-02-11 19:52:55 +00001799 bool Invalid = false;
1800
1801 // See through any implicit casts we added to fix the type.
1802 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
1803 Arg = Cast->getSubExpr();
1804
Sebastian Redl576fd422009-05-10 18:38:11 +00001805 // C++0x allows nullptr, and there's no further checking to be done for that.
1806 if (Arg->getType()->isNullPtrType())
1807 return false;
1808
Douglas Gregorccb07762009-02-11 19:52:55 +00001809 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00001810 //
Douglas Gregorccb07762009-02-11 19:52:55 +00001811 // A template-argument for a non-type, non-template
1812 // template-parameter shall be one of: [...]
1813 //
1814 // -- a pointer to member expressed as described in 5.3.1.
1815 QualifiedDeclRefExpr *DRE = 0;
1816
1817 // Ignore (and complain about) any excess parentheses.
1818 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
1819 if (!Invalid) {
Mike Stump11289f42009-09-09 15:08:12 +00001820 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00001821 diag::err_template_arg_extra_parens)
1822 << Arg->getSourceRange();
1823 Invalid = true;
1824 }
1825
1826 Arg = Parens->getSubExpr();
1827 }
1828
1829 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg))
1830 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
1831 DRE = dyn_cast<QualifiedDeclRefExpr>(UnOp->getSubExpr());
1832
1833 if (!DRE)
1834 return Diag(Arg->getSourceRange().getBegin(),
1835 diag::err_template_arg_not_pointer_to_member_form)
1836 << Arg->getSourceRange();
1837
1838 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
1839 assert((isa<FieldDecl>(DRE->getDecl()) ||
1840 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
1841 "Only non-static member pointers can make it here");
1842
1843 // Okay: this is the address of a non-static member, and therefore
1844 // a member pointer constant.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001845 Member = DRE->getDecl();
Douglas Gregorccb07762009-02-11 19:52:55 +00001846 return Invalid;
1847 }
1848
1849 // We found something else, but we don't know specifically what it is.
Mike Stump11289f42009-09-09 15:08:12 +00001850 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00001851 diag::err_template_arg_not_pointer_to_member_form)
1852 << Arg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00001853 Diag(DRE->getDecl()->getLocation(),
Douglas Gregorccb07762009-02-11 19:52:55 +00001854 diag::note_template_arg_refers_here);
1855 return true;
1856}
1857
Douglas Gregord32e0282009-02-09 23:23:08 +00001858/// \brief Check a template argument against its corresponding
1859/// non-type template parameter.
1860///
Douglas Gregor463421d2009-03-03 04:44:36 +00001861/// This routine implements the semantics of C++ [temp.arg.nontype].
1862/// It returns true if an error occurred, and false otherwise. \p
1863/// InstantiatedParamType is the type of the non-type template
1864/// parameter after it has been instantiated.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001865///
Douglas Gregor74eba0b2009-06-11 18:10:32 +00001866/// If no error was detected, Converted receives the converted template argument.
Douglas Gregord32e0282009-02-09 23:23:08 +00001867bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Mike Stump11289f42009-09-09 15:08:12 +00001868 QualType InstantiatedParamType, Expr *&Arg,
Douglas Gregor74eba0b2009-06-11 18:10:32 +00001869 TemplateArgument &Converted) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00001870 SourceLocation StartLoc = Arg->getSourceRange().getBegin();
1871
Douglas Gregor86560402009-02-10 23:36:10 +00001872 // If either the parameter has a dependent type or the argument is
1873 // type-dependent, there's nothing we can check now.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001874 // FIXME: Add template argument to Converted!
Douglas Gregorc40290e2009-03-09 23:48:35 +00001875 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
1876 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor74eba0b2009-06-11 18:10:32 +00001877 Converted = TemplateArgument(Arg);
Douglas Gregor86560402009-02-10 23:36:10 +00001878 return false;
Douglas Gregorc40290e2009-03-09 23:48:35 +00001879 }
Douglas Gregor86560402009-02-10 23:36:10 +00001880
1881 // C++ [temp.arg.nontype]p5:
1882 // The following conversions are performed on each expression used
1883 // as a non-type template-argument. If a non-type
1884 // template-argument cannot be converted to the type of the
1885 // corresponding template-parameter then the program is
1886 // ill-formed.
1887 //
1888 // -- for a non-type template-parameter of integral or
1889 // enumeration type, integral promotions (4.5) and integral
1890 // conversions (4.7) are applied.
Douglas Gregor463421d2009-03-03 04:44:36 +00001891 QualType ParamType = InstantiatedParamType;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00001892 QualType ArgType = Arg->getType();
Douglas Gregor86560402009-02-10 23:36:10 +00001893 if (ParamType->isIntegralType() || ParamType->isEnumeralType()) {
Douglas Gregor86560402009-02-10 23:36:10 +00001894 // C++ [temp.arg.nontype]p1:
1895 // A template-argument for a non-type, non-template
1896 // template-parameter shall be one of:
1897 //
1898 // -- an integral constant-expression of integral or enumeration
1899 // type; or
1900 // -- the name of a non-type template-parameter; or
1901 SourceLocation NonConstantLoc;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001902 llvm::APSInt Value;
Douglas Gregor86560402009-02-10 23:36:10 +00001903 if (!ArgType->isIntegralType() && !ArgType->isEnumeralType()) {
Mike Stump11289f42009-09-09 15:08:12 +00001904 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor86560402009-02-10 23:36:10 +00001905 diag::err_template_arg_not_integral_or_enumeral)
1906 << ArgType << Arg->getSourceRange();
1907 Diag(Param->getLocation(), diag::note_template_param_here);
1908 return true;
1909 } else if (!Arg->isValueDependent() &&
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001910 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
Douglas Gregor86560402009-02-10 23:36:10 +00001911 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
1912 << ArgType << Arg->getSourceRange();
1913 return true;
1914 }
1915
1916 // FIXME: We need some way to more easily get the unqualified form
1917 // of the types without going all the way to the
1918 // canonical type.
1919 if (Context.getCanonicalType(ParamType).getCVRQualifiers())
1920 ParamType = Context.getCanonicalType(ParamType).getUnqualifiedType();
1921 if (Context.getCanonicalType(ArgType).getCVRQualifiers())
1922 ArgType = Context.getCanonicalType(ArgType).getUnqualifiedType();
1923
1924 // Try to convert the argument to the parameter's type.
1925 if (ParamType == ArgType) {
1926 // Okay: no conversion necessary
1927 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
1928 !ParamType->isEnumeralType()) {
1929 // This is an integral promotion or conversion.
1930 ImpCastExprToType(Arg, ParamType);
1931 } else {
1932 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00001933 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor86560402009-02-10 23:36:10 +00001934 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00001935 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor86560402009-02-10 23:36:10 +00001936 Diag(Param->getLocation(), diag::note_template_param_here);
1937 return true;
1938 }
1939
Douglas Gregor52aba872009-03-14 00:20:21 +00001940 QualType IntegerType = Context.getCanonicalType(ParamType);
John McCall9dd450b2009-09-21 23:43:11 +00001941 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
Douglas Gregor74eba0b2009-06-11 18:10:32 +00001942 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregor52aba872009-03-14 00:20:21 +00001943
1944 if (!Arg->isValueDependent()) {
1945 // Check that an unsigned parameter does not receive a negative
1946 // value.
1947 if (IntegerType->isUnsignedIntegerType()
1948 && (Value.isSigned() && Value.isNegative())) {
1949 Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_negative)
1950 << Value.toString(10) << Param->getType()
1951 << Arg->getSourceRange();
1952 Diag(Param->getLocation(), diag::note_template_param_here);
1953 return true;
1954 }
1955
1956 // Check that we don't overflow the template parameter type.
1957 unsigned AllowedBits = Context.getTypeSize(IntegerType);
1958 if (Value.getActiveBits() > AllowedBits) {
Mike Stump11289f42009-09-09 15:08:12 +00001959 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor52aba872009-03-14 00:20:21 +00001960 diag::err_template_arg_too_large)
1961 << Value.toString(10) << Param->getType()
1962 << Arg->getSourceRange();
1963 Diag(Param->getLocation(), diag::note_template_param_here);
1964 return true;
1965 }
1966
1967 if (Value.getBitWidth() != AllowedBits)
1968 Value.extOrTrunc(AllowedBits);
1969 Value.setIsSigned(IntegerType->isSignedIntegerType());
1970 }
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001971
Douglas Gregor74eba0b2009-06-11 18:10:32 +00001972 // Add the value of this argument to the list of converted
1973 // arguments. We use the bitwidth and signedness of the template
1974 // parameter.
1975 if (Arg->isValueDependent()) {
1976 // The argument is value-dependent. Create a new
1977 // TemplateArgument with the converted expression.
1978 Converted = TemplateArgument(Arg);
1979 return false;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001980 }
1981
Douglas Gregor74eba0b2009-06-11 18:10:32 +00001982 Converted = TemplateArgument(StartLoc, Value,
Mike Stump11289f42009-09-09 15:08:12 +00001983 ParamType->isEnumeralType() ? ParamType
Douglas Gregor74eba0b2009-06-11 18:10:32 +00001984 : IntegerType);
Douglas Gregor86560402009-02-10 23:36:10 +00001985 return false;
1986 }
Douglas Gregor3a7796b2009-02-11 00:19:33 +00001987
Douglas Gregor6f233ef2009-02-11 01:18:59 +00001988 // Handle pointer-to-function, reference-to-function, and
1989 // pointer-to-member-function all in (roughly) the same way.
1990 if (// -- For a non-type template-parameter of type pointer to
1991 // function, only the function-to-pointer conversion (4.3) is
1992 // applied. If the template-argument represents a set of
1993 // overloaded functions (or a pointer to such), the matching
1994 // function is selected from the set (13.4).
Sebastian Redl576fd422009-05-10 18:38:11 +00001995 // In C++0x, any std::nullptr_t value can be converted.
Douglas Gregor6f233ef2009-02-11 01:18:59 +00001996 (ParamType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001997 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00001998 // -- For a non-type template-parameter of type reference to
1999 // function, no conversions apply. If the template-argument
2000 // represents a set of overloaded functions, the matching
2001 // function is selected from the set (13.4).
2002 (ParamType->isReferenceType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002003 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002004 // -- For a non-type template-parameter of type pointer to
2005 // member function, no conversions apply. If the
2006 // template-argument represents a set of overloaded member
2007 // functions, the matching member function is selected from
2008 // the set (13.4).
Sebastian Redl576fd422009-05-10 18:38:11 +00002009 // Again, C++0x allows a std::nullptr_t value.
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002010 (ParamType->isMemberPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002011 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002012 ->isFunctionType())) {
Mike Stump11289f42009-09-09 15:08:12 +00002013 if (Context.hasSameUnqualifiedType(ArgType,
Douglas Gregorccb07762009-02-11 19:52:55 +00002014 ParamType.getNonReferenceType())) {
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002015 // We don't have to do anything: the types already match.
Sebastian Redl576fd422009-05-10 18:38:11 +00002016 } else if (ArgType->isNullPtrType() && (ParamType->isPointerType() ||
2017 ParamType->isMemberPointerType())) {
2018 ArgType = ParamType;
2019 ImpCastExprToType(Arg, ParamType);
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002020 } else if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002021 ArgType = Context.getPointerType(ArgType);
2022 ImpCastExprToType(Arg, ArgType);
Mike Stump11289f42009-09-09 15:08:12 +00002023 } else if (FunctionDecl *Fn
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002024 = ResolveAddressOfOverloadedFunction(Arg, ParamType, true)) {
Douglas Gregor171c45a2009-02-18 21:56:37 +00002025 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
2026 return true;
2027
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002028 FixOverloadedFunctionReference(Arg, Fn);
2029 ArgType = Arg->getType();
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002030 if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002031 ArgType = Context.getPointerType(Arg->getType());
2032 ImpCastExprToType(Arg, ArgType);
2033 }
2034 }
2035
Mike Stump11289f42009-09-09 15:08:12 +00002036 if (!Context.hasSameUnqualifiedType(ArgType,
Douglas Gregorccb07762009-02-11 19:52:55 +00002037 ParamType.getNonReferenceType())) {
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002038 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002039 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002040 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002041 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002042 Diag(Param->getLocation(), diag::note_template_param_here);
2043 return true;
2044 }
Mike Stump11289f42009-09-09 15:08:12 +00002045
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002046 if (ParamType->isMemberPointerType()) {
2047 NamedDecl *Member = 0;
2048 if (CheckTemplateArgumentPointerToMember(Arg, Member))
2049 return true;
2050
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002051 if (Member)
2052 Member = cast<NamedDecl>(Member->getCanonicalDecl());
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002053 Converted = TemplateArgument(StartLoc, Member);
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002054 return false;
2055 }
Mike Stump11289f42009-09-09 15:08:12 +00002056
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002057 NamedDecl *Entity = 0;
2058 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2059 return true;
2060
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002061 if (Entity)
2062 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002063 Converted = TemplateArgument(StartLoc, Entity);
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002064 return false;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002065 }
2066
Chris Lattner696197c2009-02-20 21:37:53 +00002067 if (ParamType->isPointerType()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002068 // -- for a non-type template-parameter of type pointer to
2069 // object, qualification conversions (4.4) and the
2070 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl576fd422009-05-10 18:38:11 +00002071 // C++0x also allows a value of std::nullptr_t.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002072 assert(ParamType->getAs<PointerType>()->getPointeeType()->isObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002073 "Only object pointers allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00002074
Sebastian Redl576fd422009-05-10 18:38:11 +00002075 if (ArgType->isNullPtrType()) {
2076 ArgType = ParamType;
2077 ImpCastExprToType(Arg, ParamType);
2078 } else if (ArgType->isArrayType()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002079 ArgType = Context.getArrayDecayedType(ArgType);
2080 ImpCastExprToType(Arg, ArgType);
Douglas Gregora9faa442009-02-11 00:44:29 +00002081 }
Sebastian Redl576fd422009-05-10 18:38:11 +00002082
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002083 if (IsQualificationConversion(ArgType, ParamType)) {
2084 ArgType = ParamType;
2085 ImpCastExprToType(Arg, ParamType);
2086 }
Mike Stump11289f42009-09-09 15:08:12 +00002087
Douglas Gregor1515f762009-02-11 18:22:40 +00002088 if (!Context.hasSameUnqualifiedType(ArgType, ParamType)) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002089 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002090 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002091 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002092 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002093 Diag(Param->getLocation(), diag::note_template_param_here);
2094 return true;
2095 }
Mike Stump11289f42009-09-09 15:08:12 +00002096
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002097 NamedDecl *Entity = 0;
2098 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2099 return true;
2100
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002101 if (Entity)
2102 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002103 Converted = TemplateArgument(StartLoc, Entity);
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002104 return false;
Douglas Gregora9faa442009-02-11 00:44:29 +00002105 }
Mike Stump11289f42009-09-09 15:08:12 +00002106
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002107 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002108 // -- For a non-type template-parameter of type reference to
2109 // object, no conversions apply. The type referred to by the
2110 // reference may be more cv-qualified than the (otherwise
2111 // identical) type of the template-argument. The
2112 // template-parameter is bound directly to the
2113 // template-argument, which must be an lvalue.
Douglas Gregor64259f52009-03-24 20:32:41 +00002114 assert(ParamRefType->getPointeeType()->isObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002115 "Only object references allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00002116
Douglas Gregor1515f762009-02-11 18:22:40 +00002117 if (!Context.hasSameUnqualifiedType(ParamRefType->getPointeeType(), ArgType)) {
Mike Stump11289f42009-09-09 15:08:12 +00002118 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002119 diag::err_template_arg_no_ref_bind)
Douglas Gregor463421d2009-03-03 04:44:36 +00002120 << InstantiatedParamType << Arg->getType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002121 << Arg->getSourceRange();
2122 Diag(Param->getLocation(), diag::note_template_param_here);
2123 return true;
2124 }
2125
Mike Stump11289f42009-09-09 15:08:12 +00002126 unsigned ParamQuals
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002127 = Context.getCanonicalType(ParamType).getCVRQualifiers();
2128 unsigned ArgQuals = Context.getCanonicalType(ArgType).getCVRQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00002129
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002130 if ((ParamQuals | ArgQuals) != ParamQuals) {
2131 Diag(Arg->getSourceRange().getBegin(),
2132 diag::err_template_arg_ref_bind_ignores_quals)
Douglas Gregor463421d2009-03-03 04:44:36 +00002133 << InstantiatedParamType << Arg->getType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002134 << Arg->getSourceRange();
2135 Diag(Param->getLocation(), diag::note_template_param_here);
2136 return true;
2137 }
Mike Stump11289f42009-09-09 15:08:12 +00002138
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002139 NamedDecl *Entity = 0;
2140 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2141 return true;
2142
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002143 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002144 Converted = TemplateArgument(StartLoc, Entity);
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002145 return false;
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002146 }
Douglas Gregor0e558532009-02-11 16:16:59 +00002147
2148 // -- For a non-type template-parameter of type pointer to data
2149 // member, qualification conversions (4.4) are applied.
Sebastian Redl576fd422009-05-10 18:38:11 +00002150 // C++0x allows std::nullptr_t values.
Douglas Gregor0e558532009-02-11 16:16:59 +00002151 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
2152
Douglas Gregor1515f762009-02-11 18:22:40 +00002153 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
Douglas Gregor0e558532009-02-11 16:16:59 +00002154 // Types match exactly: nothing more to do here.
Sebastian Redl576fd422009-05-10 18:38:11 +00002155 } else if (ArgType->isNullPtrType()) {
2156 ImpCastExprToType(Arg, ParamType);
Douglas Gregor0e558532009-02-11 16:16:59 +00002157 } else if (IsQualificationConversion(ArgType, ParamType)) {
2158 ImpCastExprToType(Arg, ParamType);
2159 } else {
2160 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002161 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor0e558532009-02-11 16:16:59 +00002162 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002163 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor0e558532009-02-11 16:16:59 +00002164 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00002165 return true;
Douglas Gregor0e558532009-02-11 16:16:59 +00002166 }
2167
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002168 NamedDecl *Member = 0;
2169 if (CheckTemplateArgumentPointerToMember(Arg, Member))
2170 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002171
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002172 if (Member)
2173 Member = cast<NamedDecl>(Member->getCanonicalDecl());
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002174 Converted = TemplateArgument(StartLoc, Member);
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002175 return false;
Douglas Gregord32e0282009-02-09 23:23:08 +00002176}
2177
2178/// \brief Check a template argument against its corresponding
2179/// template template parameter.
2180///
2181/// This routine implements the semantics of C++ [temp.arg.template].
2182/// It returns true if an error occurred, and false otherwise.
2183bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
2184 DeclRefExpr *Arg) {
Douglas Gregor85e0f662009-02-10 00:24:35 +00002185 assert(isa<TemplateDecl>(Arg->getDecl()) && "Only template decls allowed");
2186 TemplateDecl *Template = cast<TemplateDecl>(Arg->getDecl());
2187
2188 // C++ [temp.arg.template]p1:
2189 // A template-argument for a template template-parameter shall be
2190 // the name of a class template, expressed as id-expression. Only
2191 // primary class templates are considered when matching the
2192 // template template argument with the corresponding parameter;
2193 // partial specializations are not considered even if their
2194 // parameter lists match that of the template template parameter.
Douglas Gregord5222052009-06-12 19:43:02 +00002195 //
2196 // Note that we also allow template template parameters here, which
2197 // will happen when we are dealing with, e.g., class template
2198 // partial specializations.
Mike Stump11289f42009-09-09 15:08:12 +00002199 if (!isa<ClassTemplateDecl>(Template) &&
Douglas Gregord5222052009-06-12 19:43:02 +00002200 !isa<TemplateTemplateParmDecl>(Template)) {
Mike Stump11289f42009-09-09 15:08:12 +00002201 assert(isa<FunctionTemplateDecl>(Template) &&
Douglas Gregor85e0f662009-02-10 00:24:35 +00002202 "Only function templates are possible here");
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002203 Diag(Arg->getLocStart(), diag::err_template_arg_not_class_template);
2204 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
Douglas Gregor85e0f662009-02-10 00:24:35 +00002205 << Template;
2206 }
2207
2208 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
2209 Param->getTemplateParameters(),
2210 true, true,
2211 Arg->getSourceRange().getBegin());
Douglas Gregord32e0282009-02-09 23:23:08 +00002212}
2213
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002214/// \brief Determine whether the given template parameter lists are
2215/// equivalent.
2216///
Mike Stump11289f42009-09-09 15:08:12 +00002217/// \param New The new template parameter list, typically written in the
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002218/// source code as part of a new template declaration.
2219///
2220/// \param Old The old template parameter list, typically found via
2221/// name lookup of the template declared with this template parameter
2222/// list.
2223///
2224/// \param Complain If true, this routine will produce a diagnostic if
2225/// the template parameter lists are not equivalent.
2226///
Douglas Gregor85e0f662009-02-10 00:24:35 +00002227/// \param IsTemplateTemplateParm If true, this routine is being
2228/// called to compare the template parameter lists of a template
2229/// template parameter.
2230///
2231/// \param TemplateArgLoc If this source location is valid, then we
2232/// are actually checking the template parameter list of a template
2233/// argument (New) against the template parameter list of its
2234/// corresponding template template parameter (Old). We produce
2235/// slightly different diagnostics in this scenario.
2236///
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002237/// \returns True if the template parameter lists are equal, false
2238/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002239bool
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002240Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
2241 TemplateParameterList *Old,
2242 bool Complain,
Douglas Gregor85e0f662009-02-10 00:24:35 +00002243 bool IsTemplateTemplateParm,
2244 SourceLocation TemplateArgLoc) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002245 if (Old->size() != New->size()) {
2246 if (Complain) {
Douglas Gregor85e0f662009-02-10 00:24:35 +00002247 unsigned NextDiag = diag::err_template_param_list_different_arity;
2248 if (TemplateArgLoc.isValid()) {
2249 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
2250 NextDiag = diag::note_template_param_list_different_arity;
Mike Stump11289f42009-09-09 15:08:12 +00002251 }
Douglas Gregor85e0f662009-02-10 00:24:35 +00002252 Diag(New->getTemplateLoc(), NextDiag)
2253 << (New->size() > Old->size())
2254 << IsTemplateTemplateParm
2255 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002256 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
2257 << IsTemplateTemplateParm
2258 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
2259 }
2260
2261 return false;
2262 }
2263
2264 for (TemplateParameterList::iterator OldParm = Old->begin(),
2265 OldParmEnd = Old->end(), NewParm = New->begin();
2266 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
2267 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
Douglas Gregor23061de2009-06-24 16:50:40 +00002268 if (Complain) {
2269 unsigned NextDiag = diag::err_template_param_different_kind;
2270 if (TemplateArgLoc.isValid()) {
2271 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
2272 NextDiag = diag::note_template_param_different_kind;
2273 }
2274 Diag((*NewParm)->getLocation(), NextDiag)
2275 << IsTemplateTemplateParm;
2276 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
2277 << IsTemplateTemplateParm;
Douglas Gregor85e0f662009-02-10 00:24:35 +00002278 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002279 return false;
2280 }
2281
2282 if (isa<TemplateTypeParmDecl>(*OldParm)) {
2283 // Okay; all template type parameters are equivalent (since we
Douglas Gregor85e0f662009-02-10 00:24:35 +00002284 // know we're at the same index).
2285#if 0
Mike Stump87c57ac2009-05-16 07:39:55 +00002286 // FIXME: Enable this code in debug mode *after* we properly go through
2287 // and "instantiate" the template parameter lists of template template
2288 // parameters. It's only after this instantiation that (1) any dependent
2289 // types within the template parameter list of the template template
2290 // parameter can be checked, and (2) the template type parameter depths
Douglas Gregor85e0f662009-02-10 00:24:35 +00002291 // will match up.
Mike Stump11289f42009-09-09 15:08:12 +00002292 QualType OldParmType
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002293 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*OldParm));
Mike Stump11289f42009-09-09 15:08:12 +00002294 QualType NewParmType
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002295 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*NewParm));
Mike Stump11289f42009-09-09 15:08:12 +00002296 assert(Context.getCanonicalType(OldParmType) ==
2297 Context.getCanonicalType(NewParmType) &&
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002298 "type parameter mismatch?");
2299#endif
Mike Stump11289f42009-09-09 15:08:12 +00002300 } else if (NonTypeTemplateParmDecl *OldNTTP
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002301 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
2302 // The types of non-type template parameters must agree.
2303 NonTypeTemplateParmDecl *NewNTTP
2304 = cast<NonTypeTemplateParmDecl>(*NewParm);
2305 if (Context.getCanonicalType(OldNTTP->getType()) !=
2306 Context.getCanonicalType(NewNTTP->getType())) {
2307 if (Complain) {
Douglas Gregor85e0f662009-02-10 00:24:35 +00002308 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
2309 if (TemplateArgLoc.isValid()) {
Mike Stump11289f42009-09-09 15:08:12 +00002310 Diag(TemplateArgLoc,
Douglas Gregor85e0f662009-02-10 00:24:35 +00002311 diag::err_template_arg_template_params_mismatch);
2312 NextDiag = diag::note_template_nontype_parm_different_type;
2313 }
2314 Diag(NewNTTP->getLocation(), NextDiag)
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002315 << NewNTTP->getType()
2316 << IsTemplateTemplateParm;
Mike Stump11289f42009-09-09 15:08:12 +00002317 Diag(OldNTTP->getLocation(),
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002318 diag::note_template_nontype_parm_prev_declaration)
2319 << OldNTTP->getType();
2320 }
2321 return false;
2322 }
2323 } else {
2324 // The template parameter lists of template template
2325 // parameters must agree.
2326 // FIXME: Could we perform a faster "type" comparison here?
Mike Stump11289f42009-09-09 15:08:12 +00002327 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002328 "Only template template parameters handled here");
Mike Stump11289f42009-09-09 15:08:12 +00002329 TemplateTemplateParmDecl *OldTTP
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002330 = cast<TemplateTemplateParmDecl>(*OldParm);
2331 TemplateTemplateParmDecl *NewTTP
2332 = cast<TemplateTemplateParmDecl>(*NewParm);
2333 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
2334 OldTTP->getTemplateParameters(),
2335 Complain,
Douglas Gregor85e0f662009-02-10 00:24:35 +00002336 /*IsTemplateTemplateParm=*/true,
2337 TemplateArgLoc))
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002338 return false;
2339 }
2340 }
2341
2342 return true;
2343}
2344
2345/// \brief Check whether a template can be declared within this scope.
2346///
2347/// If the template declaration is valid in this scope, returns
2348/// false. Otherwise, issues a diagnostic and returns true.
Mike Stump11289f42009-09-09 15:08:12 +00002349bool
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002350Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002351 // Find the nearest enclosing declaration scope.
2352 while ((S->getFlags() & Scope::DeclScope) == 0 ||
2353 (S->getFlags() & Scope::TemplateParamScope) != 0)
2354 S = S->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00002355
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002356 // C++ [temp]p2:
2357 // A template-declaration can appear only as a namespace scope or
2358 // class scope declaration.
2359 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
Eli Friedmandfbd0c42009-07-31 01:43:05 +00002360 if (Ctx && isa<LinkageSpecDecl>(Ctx) &&
2361 cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
Mike Stump11289f42009-09-09 15:08:12 +00002362 return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002363 << TemplateParams->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002364
Eli Friedmandfbd0c42009-07-31 01:43:05 +00002365 while (Ctx && isa<LinkageSpecDecl>(Ctx))
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002366 Ctx = Ctx->getParent();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002367
2368 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
2369 return false;
2370
Mike Stump11289f42009-09-09 15:08:12 +00002371 return Diag(TemplateParams->getTemplateLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002372 diag::err_template_outside_namespace_or_class_scope)
2373 << TemplateParams->getSourceRange();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002374}
Douglas Gregor67a65642009-02-17 23:15:12 +00002375
Douglas Gregor54888652009-10-07 00:13:32 +00002376/// \brief Determine what kind of template specialization the given declaration
2377/// is.
2378static TemplateSpecializationKind getTemplateSpecializationKind(NamedDecl *D) {
2379 if (!D)
2380 return TSK_Undeclared;
2381
Douglas Gregorbbe8f462009-10-08 15:14:33 +00002382 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
2383 return Record->getTemplateSpecializationKind();
Douglas Gregor54888652009-10-07 00:13:32 +00002384 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
2385 return Function->getTemplateSpecializationKind();
Douglas Gregor86d142a2009-10-08 07:24:58 +00002386 if (VarDecl *Var = dyn_cast<VarDecl>(D))
2387 return Var->getTemplateSpecializationKind();
2388
Douglas Gregor54888652009-10-07 00:13:32 +00002389 return TSK_Undeclared;
2390}
2391
2392/// \brief Check whether a specialization or explicit instantiation is
2393/// well-formed in the current context.
Douglas Gregorf47b9112009-02-25 22:02:03 +00002394///
Douglas Gregor54888652009-10-07 00:13:32 +00002395/// This routine determines whether a template specialization or
Mike Stump11289f42009-09-09 15:08:12 +00002396/// explicit instantiation can be declared in the current context
Douglas Gregor54888652009-10-07 00:13:32 +00002397/// (C++ [temp.expl.spec]p2, C++0x [temp.explicit]p2).
2398///
2399/// \param S the semantic analysis object for which this check is being
2400/// performed.
2401///
2402/// \param Specialized the entity being specialized or instantiated, which
2403/// may be a kind of template (class template, function template, etc.) or
2404/// a member of a class template (member function, static data member,
2405/// member class).
2406///
2407/// \param PrevDecl the previous declaration of this entity, if any.
2408///
2409/// \param Loc the location of the explicit specialization or instantiation of
2410/// this entity.
2411///
2412/// \param IsPartialSpecialization whether this is a partial specialization of
2413/// a class template.
2414///
2415/// \param TSK the kind of specialization or implicit instantiation being
2416/// performed.
2417///
2418/// \returns true if there was an error that we cannot recover from, false
2419/// otherwise.
2420static bool CheckTemplateSpecializationScope(Sema &S,
2421 NamedDecl *Specialized,
2422 NamedDecl *PrevDecl,
2423 SourceLocation Loc,
2424 bool IsPartialSpecialization,
2425 TemplateSpecializationKind TSK) {
2426 // Keep these "kind" numbers in sync with the %select statements in the
2427 // various diagnostics emitted by this routine.
2428 int EntityKind = 0;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00002429 bool isTemplateSpecialization = false;
2430 if (isa<ClassTemplateDecl>(Specialized)) {
Douglas Gregor54888652009-10-07 00:13:32 +00002431 EntityKind = IsPartialSpecialization? 1 : 0;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00002432 isTemplateSpecialization = true;
2433 } else if (isa<FunctionTemplateDecl>(Specialized)) {
Douglas Gregor54888652009-10-07 00:13:32 +00002434 EntityKind = 2;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00002435 isTemplateSpecialization = true;
2436 } else if (isa<CXXMethodDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00002437 EntityKind = 3;
2438 else if (isa<VarDecl>(Specialized))
2439 EntityKind = 4;
2440 else if (isa<RecordDecl>(Specialized))
2441 EntityKind = 5;
2442 else {
2443 S.Diag(Loc, diag::err_template_spec_unknown_kind) << TSK;
2444 S.Diag(Specialized->getLocation(), diag::note_specialized_entity) << TSK;
2445 return true;
2446 }
2447
Douglas Gregorf47b9112009-02-25 22:02:03 +00002448 // C++ [temp.expl.spec]p2:
2449 // An explicit specialization shall be declared in the namespace
2450 // of which the template is a member, or, for member templates, in
2451 // the namespace of which the enclosing class or enclosing class
2452 // template is a member. An explicit specialization of a member
2453 // function, member class or static data member of a class
2454 // template shall be declared in the namespace of which the class
2455 // template is a member. Such a declaration may also be a
2456 // definition. If the declaration is not a definition, the
2457 // specialization may be defined later in the name- space in which
2458 // the explicit specialization was declared, or in a namespace
2459 // that encloses the one in which the explicit specialization was
2460 // declared.
Douglas Gregor54888652009-10-07 00:13:32 +00002461 if (S.CurContext->getLookupContext()->isFunctionOrMethod()) {
2462 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
2463 << TSK << Specialized;
Douglas Gregorf47b9112009-02-25 22:02:03 +00002464 return true;
2465 }
Douglas Gregore4b05162009-10-07 17:21:34 +00002466
Douglas Gregor40fb7442009-10-07 17:30:37 +00002467 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
2468 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
2469 << TSK << Specialized;
2470 return true;
2471 }
2472
Douglas Gregore4b05162009-10-07 17:21:34 +00002473 // C++ [temp.class.spec]p6:
2474 // A class template partial specialization may be declared or redeclared
2475 // in any namespace scope in which its definition may be defined (14.5.1
2476 // and 14.5.2).
Douglas Gregor54888652009-10-07 00:13:32 +00002477 bool ComplainedAboutScope = false;
Douglas Gregore4b05162009-10-07 17:21:34 +00002478 DeclContext *SpecializedContext
Douglas Gregor54888652009-10-07 00:13:32 +00002479 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregore4b05162009-10-07 17:21:34 +00002480 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
Douglas Gregor54888652009-10-07 00:13:32 +00002481 if (TSK == TSK_ExplicitSpecialization) {
Douglas Gregor54888652009-10-07 00:13:32 +00002482 if ((!PrevDecl ||
2483 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
2484 getTemplateSpecializationKind(PrevDecl) == TSK_ImplicitInstantiation)){
2485 // There is no prior declaration of this entity, so this
2486 // specialization must be in the same context as the template
2487 // itself.
2488 if (!DC->Equals(SpecializedContext)) {
2489 if (isa<TranslationUnitDecl>(SpecializedContext))
2490 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global)
2491 << EntityKind << Specialized;
2492 else if (isa<NamespaceDecl>(SpecializedContext))
2493 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope)
2494 << EntityKind << Specialized
2495 << cast<NamedDecl>(SpecializedContext);
2496
Douglas Gregor5c0405d2009-10-07 22:35:40 +00002497 S.Diag(Specialized->getLocation(), diag::note_specialized_entity)
2498 << TSK;
Douglas Gregor54888652009-10-07 00:13:32 +00002499 ComplainedAboutScope = true;
2500 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00002501 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00002502 }
Douglas Gregor54888652009-10-07 00:13:32 +00002503
2504 // Make sure that this redeclaration (or definition) occurs in an enclosing
2505 // namespace. We perform this check for explicit specializations and, in
2506 // C++0x, for explicit instantiations as well (per DR275).
2507 // FIXME: -Wc++0x should make these warnings.
2508 // Note that HandleDeclarator() performs this check for explicit
2509 // specializations of function templates, static data members, and member
2510 // functions, so we skip the check here for those kinds of entities.
2511 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
Douglas Gregore4b05162009-10-07 17:21:34 +00002512 // Should we refactor that check, so that it occurs later?
2513 if (!ComplainedAboutScope && !DC->Encloses(SpecializedContext) &&
Douglas Gregor54888652009-10-07 00:13:32 +00002514 ((TSK == TSK_ExplicitSpecialization &&
2515 !(isa<FunctionTemplateDecl>(Specialized) || isa<VarDecl>(Specialized) ||
2516 isa<FunctionDecl>(Specialized))) ||
2517 S.getLangOptions().CPlusPlus0x)) {
2518 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 Gregor5c0405d2009-10-07 22:35:40 +00002526 S.Diag(Specialized->getLocation(), diag::note_specialized_entity) << TSK;
Douglas Gregorf47b9112009-02-25 22:02:03 +00002527 }
Douglas Gregor54888652009-10-07 00:13:32 +00002528
2529 // FIXME: check for specialization-after-instantiation errors and such.
2530
Douglas Gregorf47b9112009-02-25 22:02:03 +00002531 return false;
2532}
Douglas Gregor54888652009-10-07 00:13:32 +00002533
Douglas Gregor8cfd2ba2009-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 Gregor09a30232009-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 Gregor8cfd2ba2009-06-12 21:21:02 +00002549/// \returns true if there was an error, false otherwise.
2550bool Sema::CheckClassTemplatePartialSpecializationArgs(
2551 TemplateParameterList *TemplateParams,
Anders Carlsson40c1d492009-06-13 18:20:51 +00002552 const TemplateArgumentListBuilder &TemplateArgs,
Douglas Gregor09a30232009-06-12 22:08:06 +00002553 bool &MirrorsPrimaryTemplate) {
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002554 // FIXME: the interface to this function will have to change to
2555 // accommodate variadic templates.
Douglas Gregor09a30232009-06-12 22:08:06 +00002556 MirrorsPrimaryTemplate = true;
Mike Stump11289f42009-09-09 15:08:12 +00002557
Anders Carlsson5947ddf2009-06-23 01:26:57 +00002558 const TemplateArgument *ArgList = TemplateArgs.getFlatArguments();
Mike Stump11289f42009-09-09 15:08:12 +00002559
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002560 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
Douglas Gregor09a30232009-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 Stump11289f42009-09-09 15:08:12 +00002566 if (TemplateTypeParmDecl *TTP
Douglas Gregor09a30232009-06-12 22:08:06 +00002567 = dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(I))) {
2568 if (Context.getCanonicalType(Context.getTypeDeclType(TTP)) !=
Anders Carlsson40c1d492009-06-13 18:20:51 +00002569 Context.getCanonicalType(ArgList[I].getAsType()))
Douglas Gregor09a30232009-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 Stump11289f42009-09-09 15:08:12 +00002576 TemplateTemplateParmDecl *ArgDecl
Douglas Gregor09a30232009-06-12 22:08:06 +00002577 = dyn_cast_or_null<TemplateTemplateParmDecl>(
Anders Carlsson40c1d492009-06-13 18:20:51 +00002578 ArgList[I].getAsDecl());
Douglas Gregor09a30232009-06-12 22:08:06 +00002579 if (!ArgDecl)
Mike Stump11289f42009-09-09 15:08:12 +00002580 if (DeclRefExpr *DRE
Anders Carlsson40c1d492009-06-13 18:20:51 +00002581 = dyn_cast_or_null<DeclRefExpr>(ArgList[I].getAsExpr()))
Douglas Gregor09a30232009-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 Stump11289f42009-09-09 15:08:12 +00002591 NonTypeTemplateParmDecl *Param
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002592 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
Douglas Gregor09a30232009-06-12 22:08:06 +00002593 if (!Param) {
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002594 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00002595 }
2596
Anders Carlsson40c1d492009-06-13 18:20:51 +00002597 Expr *ArgExpr = ArgList[I].getAsExpr();
Douglas Gregor09a30232009-06-12 22:08:06 +00002598 if (!ArgExpr) {
2599 MirrorsPrimaryTemplate = false;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002600 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00002601 }
Douglas Gregor8cfd2ba2009-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 Stump11289f42009-09-09 15:08:12 +00002612 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor09a30232009-06-12 22:08:06 +00002613 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00002614 if (MirrorsPrimaryTemplate &&
Douglas Gregor09a30232009-06-12 22:08:06 +00002615 (Param->getIndex() != NTTP->getIndex() ||
2616 Param->getDepth() != NTTP->getDepth()))
2617 MirrorsPrimaryTemplate = false;
2618
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002619 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00002620 }
Douglas Gregor8cfd2ba2009-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 Stump11289f42009-09-09 15:08:12 +00002630 Diag(ArgExpr->getLocStart(),
Douglas Gregor8cfd2ba2009-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 Stump11289f42009-09-09 15:08:12 +00002640 Diag(ArgExpr->getLocStart(),
Douglas Gregor8cfd2ba2009-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 Gregor09a30232009-06-12 22:08:06 +00002647
2648 MirrorsPrimaryTemplate = false;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002649 }
2650
2651 return false;
2652}
2653
Douglas Gregorc08f4892009-03-25 00:13:59 +00002654Sema::DeclResult
John McCall9bb74a52009-07-31 02:45:11 +00002655Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
2656 TagUseKind TUK,
Mike Stump11289f42009-09-09 15:08:12 +00002657 SourceLocation KWLoc,
Douglas Gregor67a65642009-02-17 23:15:12 +00002658 const CXXScopeSpec &SS,
Douglas Gregordc572a32009-03-30 22:58:21 +00002659 TemplateTy TemplateD,
Douglas Gregor67a65642009-02-17 23:15:12 +00002660 SourceLocation TemplateNameLoc,
2661 SourceLocation LAngleLoc,
Douglas Gregorc40290e2009-03-09 23:48:35 +00002662 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregor67a65642009-02-17 23:15:12 +00002663 SourceLocation *TemplateArgLocs,
2664 SourceLocation RAngleLoc,
2665 AttributeList *Attr,
2666 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregor2208a292009-09-26 20:57:03 +00002667 assert(TUK != TUK_Reference && "References are not specializations");
John McCall06f6fe8d2009-09-04 01:14:41 +00002668
Douglas Gregor67a65642009-02-17 23:15:12 +00002669 // Find the class template we're specializing
Douglas Gregordc572a32009-03-30 22:58:21 +00002670 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump11289f42009-09-09 15:08:12 +00002671 ClassTemplateDecl *ClassTemplate
Douglas Gregordc572a32009-03-30 22:58:21 +00002672 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
Douglas Gregor67a65642009-02-17 23:15:12 +00002673
Douglas Gregor5c0405d2009-10-07 22:35:40 +00002674 bool isExplicitSpecialization = false;
Douglas Gregor2373c592009-05-31 09:31:02 +00002675 bool isPartialSpecialization = false;
2676
Douglas Gregorf47b9112009-02-25 22:02:03 +00002677 // Check the validity of the template headers that introduce this
2678 // template.
Douglas Gregor2208a292009-09-26 20:57:03 +00002679 // FIXME: We probably shouldn't complain about these headers for
2680 // friend declarations.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002681 TemplateParameterList *TemplateParams
Mike Stump11289f42009-09-09 15:08:12 +00002682 = MatchTemplateParametersToScopeSpecifier(TemplateNameLoc, SS,
2683 (TemplateParameterList**)TemplateParameterLists.get(),
Douglas Gregor5c0405d2009-10-07 22:35:40 +00002684 TemplateParameterLists.size(),
2685 isExplicitSpecialization);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002686 if (TemplateParams && TemplateParams->size() > 0) {
2687 isPartialSpecialization = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00002688
Douglas Gregor1d5e9f92009-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 Stump11289f42009-09-09 15:08:12 +00002696 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-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 Stump11289f42009-09-09 15:08:12 +00002703 Diag(NTTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-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 Stump11289f42009-09-09 15:08:12 +00002712 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-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 Gregord5222052009-06-12 19:43:02 +00002717 }
2718 }
2719 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00002720 } else if (!TemplateParams && TUK != TUK_Friend) {
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002721 Diag(KWLoc, diag::err_template_spec_needs_header)
2722 << CodeModificationHint::CreateInsertion(KWLoc, "template<> ");
Douglas Gregor5c0405d2009-10-07 22:35:40 +00002723 isExplicitSpecialization = true;
2724 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00002725
Douglas Gregor67a65642009-02-17 23:15:12 +00002726 // Check that the specialization uses the same tag kind as the
2727 // original template.
2728 TagDecl::TagKind Kind;
2729 switch (TagSpec) {
2730 default: assert(0 && "Unknown tag type!");
2731 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2732 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2733 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2734 }
Douglas Gregord9034f02009-05-14 16:41:31 +00002735 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump11289f42009-09-09 15:08:12 +00002736 Kind, KWLoc,
Douglas Gregord9034f02009-05-14 16:41:31 +00002737 *ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00002738 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00002739 << ClassTemplate
Mike Stump11289f42009-09-09 15:08:12 +00002740 << CodeModificationHint::CreateReplacement(KWLoc,
Douglas Gregor170512f2009-04-01 23:51:29 +00002741 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00002742 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregor67a65642009-02-17 23:15:12 +00002743 diag::note_previous_use);
2744 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
2745 }
2746
Douglas Gregorc40290e2009-03-09 23:48:35 +00002747 // Translate the parser's template argument list in our AST format.
2748 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
2749 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
2750
Douglas Gregor67a65642009-02-17 23:15:12 +00002751 // Check that the template argument list is well-formed for this
2752 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00002753 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
2754 TemplateArgs.size());
Mike Stump11289f42009-09-09 15:08:12 +00002755 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
Anders Carlsson40c1d492009-06-13 18:20:51 +00002756 TemplateArgs.data(), TemplateArgs.size(),
Douglas Gregore3f1f352009-07-01 00:28:38 +00002757 RAngleLoc, false, Converted))
Douglas Gregorc08f4892009-03-25 00:13:59 +00002758 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00002759
Mike Stump11289f42009-09-09 15:08:12 +00002760 assert((Converted.structuredSize() ==
Douglas Gregor67a65642009-02-17 23:15:12 +00002761 ClassTemplate->getTemplateParameters()->size()) &&
2762 "Converted template argument list is too short!");
Mike Stump11289f42009-09-09 15:08:12 +00002763
Douglas Gregor2373c592009-05-31 09:31:02 +00002764 // Find the class template (partial) specialization declaration that
Douglas Gregor67a65642009-02-17 23:15:12 +00002765 // corresponds to these arguments.
2766 llvm::FoldingSetNodeID ID;
Douglas Gregord5222052009-06-12 19:43:02 +00002767 if (isPartialSpecialization) {
Douglas Gregor09a30232009-06-12 22:08:06 +00002768 bool MirrorsPrimaryTemplate;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002769 if (CheckClassTemplatePartialSpecializationArgs(
2770 ClassTemplate->getTemplateParameters(),
Anders Carlsson5947ddf2009-06-23 01:26:57 +00002771 Converted, MirrorsPrimaryTemplate))
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002772 return true;
2773
Douglas Gregor09a30232009-06-12 22:08:06 +00002774 if (MirrorsPrimaryTemplate) {
2775 // C++ [temp.class.spec]p9b3:
2776 //
Mike Stump11289f42009-09-09 15:08:12 +00002777 // -- The argument list of the specialization shall not be identical
2778 // to the implicit argument list of the primary template.
Douglas Gregor09a30232009-06-12 22:08:06 +00002779 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
John McCall9bb74a52009-07-31 02:45:11 +00002780 << (TUK == TUK_Definition)
Mike Stump11289f42009-09-09 15:08:12 +00002781 << CodeModificationHint::CreateRemoval(SourceRange(LAngleLoc,
Douglas Gregor09a30232009-06-12 22:08:06 +00002782 RAngleLoc));
John McCall9bb74a52009-07-31 02:45:11 +00002783 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
Douglas Gregor09a30232009-06-12 22:08:06 +00002784 ClassTemplate->getIdentifier(),
2785 TemplateNameLoc,
2786 Attr,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002787 TemplateParams,
Douglas Gregor09a30232009-06-12 22:08:06 +00002788 AS_none);
2789 }
2790
Douglas Gregor2208a292009-09-26 20:57:03 +00002791 // FIXME: Diagnose friend partial specializations
2792
Douglas Gregor2373c592009-05-31 09:31:02 +00002793 // FIXME: Template parameter list matters, too
Mike Stump11289f42009-09-09 15:08:12 +00002794 ClassTemplatePartialSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00002795 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00002796 Converted.flatSize(),
2797 Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00002798 } else
Anders Carlsson8aa89d42009-06-05 03:43:12 +00002799 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00002800 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00002801 Converted.flatSize(),
2802 Context);
Douglas Gregor67a65642009-02-17 23:15:12 +00002803 void *InsertPos = 0;
Douglas Gregor2373c592009-05-31 09:31:02 +00002804 ClassTemplateSpecializationDecl *PrevDecl = 0;
2805
2806 if (isPartialSpecialization)
2807 PrevDecl
Mike Stump11289f42009-09-09 15:08:12 +00002808 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
Douglas Gregor2373c592009-05-31 09:31:02 +00002809 InsertPos);
2810 else
2811 PrevDecl
2812 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor67a65642009-02-17 23:15:12 +00002813
2814 ClassTemplateSpecializationDecl *Specialization = 0;
2815
Douglas Gregorf47b9112009-02-25 22:02:03 +00002816 // Check whether we can declare a class template specialization in
2817 // the current scope.
Douglas Gregor2208a292009-09-26 20:57:03 +00002818 if (TUK != TUK_Friend &&
Douglas Gregor54888652009-10-07 00:13:32 +00002819 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
2820 TemplateNameLoc, isPartialSpecialization,
2821 TSK_ExplicitSpecialization))
Douglas Gregorc08f4892009-03-25 00:13:59 +00002822 return true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00002823
Douglas Gregor15301382009-07-30 17:40:51 +00002824 // The canonical type
2825 QualType CanonType;
Douglas Gregor2208a292009-09-26 20:57:03 +00002826 if (PrevDecl &&
2827 (PrevDecl->getSpecializationKind() == TSK_Undeclared ||
2828 TUK == TUK_Friend)) {
Douglas Gregor67a65642009-02-17 23:15:12 +00002829 // Since the only prior class template specialization with these
Douglas Gregor2208a292009-09-26 20:57:03 +00002830 // arguments was referenced but not declared, or we're only
2831 // referencing this specialization as a friend, reuse that
Douglas Gregor67a65642009-02-17 23:15:12 +00002832 // declaration node as our own, updating its source location to
2833 // reflect our new declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00002834 Specialization = PrevDecl;
Douglas Gregor1e249f82009-02-25 22:18:32 +00002835 Specialization->setLocation(TemplateNameLoc);
Douglas Gregor67a65642009-02-17 23:15:12 +00002836 PrevDecl = 0;
Douglas Gregor15301382009-07-30 17:40:51 +00002837 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregor2373c592009-05-31 09:31:02 +00002838 } else if (isPartialSpecialization) {
Douglas Gregor15301382009-07-30 17:40:51 +00002839 // Build the canonical type that describes the converted template
2840 // arguments of the class template partial specialization.
2841 CanonType = Context.getTemplateSpecializationType(
2842 TemplateName(ClassTemplate),
2843 Converted.getFlatArguments(),
2844 Converted.flatSize());
2845
Douglas Gregor2373c592009-05-31 09:31:02 +00002846 // Create a new class template partial specialization declaration node.
Mike Stump11289f42009-09-09 15:08:12 +00002847 TemplateParameterList *TemplateParams
Douglas Gregor2373c592009-05-31 09:31:02 +00002848 = static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
2849 ClassTemplatePartialSpecializationDecl *PrevPartial
2850 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
Mike Stump11289f42009-09-09 15:08:12 +00002851 ClassTemplatePartialSpecializationDecl *Partial
2852 = ClassTemplatePartialSpecializationDecl::Create(Context,
Douglas Gregor2373c592009-05-31 09:31:02 +00002853 ClassTemplate->getDeclContext(),
Anders Carlsson1b28c3e2009-06-05 04:06:48 +00002854 TemplateNameLoc,
2855 TemplateParams,
2856 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00002857 Converted,
Anders Carlsson1b28c3e2009-06-05 04:06:48 +00002858 PrevPartial);
Douglas Gregor2373c592009-05-31 09:31:02 +00002859
2860 if (PrevPartial) {
2861 ClassTemplate->getPartialSpecializations().RemoveNode(PrevPartial);
2862 ClassTemplate->getPartialSpecializations().GetOrInsertNode(Partial);
2863 } else {
2864 ClassTemplate->getPartialSpecializations().InsertNode(Partial, InsertPos);
2865 }
2866 Specialization = Partial;
Douglas Gregor91772d12009-06-13 00:26:55 +00002867
2868 // Check that all of the template parameters of the class template
2869 // partial specialization are deducible from the template
2870 // arguments. If not, this class template partial specialization
2871 // will never be used.
2872 llvm::SmallVector<bool, 8> DeducibleParams;
2873 DeducibleParams.resize(TemplateParams->size());
Douglas Gregore1d2ef32009-09-14 21:25:05 +00002874 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
2875 DeducibleParams);
Douglas Gregor91772d12009-06-13 00:26:55 +00002876 unsigned NumNonDeducible = 0;
2877 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I)
2878 if (!DeducibleParams[I])
2879 ++NumNonDeducible;
2880
2881 if (NumNonDeducible) {
2882 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
2883 << (NumNonDeducible > 1)
2884 << SourceRange(TemplateNameLoc, RAngleLoc);
2885 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
2886 if (!DeducibleParams[I]) {
2887 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
2888 if (Param->getDeclName())
Mike Stump11289f42009-09-09 15:08:12 +00002889 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00002890 diag::note_partial_spec_unused_parameter)
2891 << Param->getDeclName();
2892 else
Mike Stump11289f42009-09-09 15:08:12 +00002893 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00002894 diag::note_partial_spec_unused_parameter)
2895 << std::string("<anonymous>");
2896 }
2897 }
2898 }
Douglas Gregor67a65642009-02-17 23:15:12 +00002899 } else {
2900 // Create a new class template specialization declaration node for
Douglas Gregor2208a292009-09-26 20:57:03 +00002901 // this explicit specialization or friend declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00002902 Specialization
Mike Stump11289f42009-09-09 15:08:12 +00002903 = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregor67a65642009-02-17 23:15:12 +00002904 ClassTemplate->getDeclContext(),
2905 TemplateNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +00002906 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00002907 Converted,
Douglas Gregor67a65642009-02-17 23:15:12 +00002908 PrevDecl);
2909
2910 if (PrevDecl) {
2911 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
2912 ClassTemplate->getSpecializations().GetOrInsertNode(Specialization);
2913 } else {
Mike Stump11289f42009-09-09 15:08:12 +00002914 ClassTemplate->getSpecializations().InsertNode(Specialization,
Douglas Gregor67a65642009-02-17 23:15:12 +00002915 InsertPos);
2916 }
Douglas Gregor15301382009-07-30 17:40:51 +00002917
2918 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00002919 }
2920
Douglas Gregor2208a292009-09-26 20:57:03 +00002921 // If this is not a friend, note that this is an explicit specialization.
2922 if (TUK != TUK_Friend)
2923 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00002924
2925 // Check that this isn't a redefinition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00002926 if (TUK == TUK_Definition) {
Douglas Gregor67a65642009-02-17 23:15:12 +00002927 if (RecordDecl *Def = Specialization->getDefinition(Context)) {
Mike Stump87c57ac2009-05-16 07:39:55 +00002928 // FIXME: Should also handle explicit specialization after implicit
2929 // instantiation with a special diagnostic.
Douglas Gregor67a65642009-02-17 23:15:12 +00002930 SourceRange Range(TemplateNameLoc, RAngleLoc);
Mike Stump11289f42009-09-09 15:08:12 +00002931 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregor2373c592009-05-31 09:31:02 +00002932 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregor67a65642009-02-17 23:15:12 +00002933 Diag(Def->getLocation(), diag::note_previous_definition);
2934 Specialization->setInvalidDecl();
Douglas Gregorc08f4892009-03-25 00:13:59 +00002935 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00002936 }
2937 }
2938
Douglas Gregord56a91e2009-02-26 22:19:44 +00002939 // Build the fully-sugared type for this class template
2940 // specialization as the user wrote in the specialization
2941 // itself. This means that we'll pretty-print the type retrieved
2942 // from the specialization's declaration the way that the user
2943 // actually wrote the specialization, rather than formatting the
2944 // name based on the "canonical" representation used to store the
2945 // template arguments in the specialization.
Mike Stump11289f42009-09-09 15:08:12 +00002946 QualType WrittenTy
2947 = Context.getTemplateSpecializationType(Name,
Anders Carlsson40c1d492009-06-13 18:20:51 +00002948 TemplateArgs.data(),
Douglas Gregordc572a32009-03-30 22:58:21 +00002949 TemplateArgs.size(),
Douglas Gregor15301382009-07-30 17:40:51 +00002950 CanonType);
Douglas Gregor2208a292009-09-26 20:57:03 +00002951 if (TUK != TUK_Friend)
2952 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregorc40290e2009-03-09 23:48:35 +00002953 TemplateArgsIn.release();
Douglas Gregor67a65642009-02-17 23:15:12 +00002954
Douglas Gregor1e249f82009-02-25 22:18:32 +00002955 // C++ [temp.expl.spec]p9:
2956 // A template explicit specialization is in the scope of the
2957 // namespace in which the template was defined.
2958 //
2959 // We actually implement this paragraph where we set the semantic
2960 // context (in the creation of the ClassTemplateSpecializationDecl),
2961 // but we also maintain the lexical context where the actual
2962 // definition occurs.
Douglas Gregor67a65642009-02-17 23:15:12 +00002963 Specialization->setLexicalDeclContext(CurContext);
Mike Stump11289f42009-09-09 15:08:12 +00002964
Douglas Gregor67a65642009-02-17 23:15:12 +00002965 // We may be starting the definition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00002966 if (TUK == TUK_Definition)
Douglas Gregor67a65642009-02-17 23:15:12 +00002967 Specialization->startDefinition();
2968
Douglas Gregor2208a292009-09-26 20:57:03 +00002969 if (TUK == TUK_Friend) {
2970 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
2971 TemplateNameLoc,
2972 WrittenTy.getTypePtr(),
2973 /*FIXME:*/KWLoc);
2974 Friend->setAccess(AS_public);
2975 CurContext->addDecl(Friend);
2976 } else {
2977 // Add the specialization into its lexical context, so that it can
2978 // be seen when iterating through the list of declarations in that
2979 // context. However, specializations are not found by name lookup.
2980 CurContext->addDecl(Specialization);
2981 }
Chris Lattner83f095c2009-03-28 19:18:32 +00002982 return DeclPtrTy::make(Specialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00002983}
Douglas Gregor333489b2009-03-27 23:10:48 +00002984
Mike Stump11289f42009-09-09 15:08:12 +00002985Sema::DeclPtrTy
2986Sema::ActOnTemplateDeclarator(Scope *S,
Douglas Gregorb52fabb2009-06-23 23:11:28 +00002987 MultiTemplateParamsArg TemplateParameterLists,
2988 Declarator &D) {
2989 return HandleDeclarator(S, D, move(TemplateParameterLists), false);
2990}
2991
Mike Stump11289f42009-09-09 15:08:12 +00002992Sema::DeclPtrTy
2993Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
Douglas Gregor17a7c122009-06-24 00:54:41 +00002994 MultiTemplateParamsArg TemplateParameterLists,
2995 Declarator &D) {
2996 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
2997 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
2998 "Not a function declarator!");
2999 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Mike Stump11289f42009-09-09 15:08:12 +00003000
Douglas Gregor17a7c122009-06-24 00:54:41 +00003001 if (FTI.hasPrototype) {
Mike Stump11289f42009-09-09 15:08:12 +00003002 // FIXME: Diagnose arguments without names in C.
Douglas Gregor17a7c122009-06-24 00:54:41 +00003003 }
Mike Stump11289f42009-09-09 15:08:12 +00003004
Douglas Gregor17a7c122009-06-24 00:54:41 +00003005 Scope *ParentScope = FnBodyScope->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00003006
3007 DeclPtrTy DP = HandleDeclarator(ParentScope, D,
Douglas Gregor17a7c122009-06-24 00:54:41 +00003008 move(TemplateParameterLists),
3009 /*IsFunctionDefinition=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00003010 if (FunctionTemplateDecl *FunctionTemplate
Douglas Gregord8d297c2009-07-21 23:53:31 +00003011 = dyn_cast_or_null<FunctionTemplateDecl>(DP.getAs<Decl>()))
Mike Stump11289f42009-09-09 15:08:12 +00003012 return ActOnStartOfFunctionDef(FnBodyScope,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003013 DeclPtrTy::make(FunctionTemplate->getTemplatedDecl()));
Douglas Gregord8d297c2009-07-21 23:53:31 +00003014 if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(DP.getAs<Decl>()))
3015 return ActOnStartOfFunctionDef(FnBodyScope, DeclPtrTy::make(Function));
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003016 return DeclPtrTy();
Douglas Gregor17a7c122009-06-24 00:54:41 +00003017}
3018
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003019/// \brief Perform semantic analysis for the given function template
3020/// specialization.
3021///
3022/// This routine performs all of the semantic analysis required for an
3023/// explicit function template specialization. On successful completion,
3024/// the function declaration \p FD will become a function template
3025/// specialization.
3026///
3027/// \param FD the function declaration, which will be updated to become a
3028/// function template specialization.
3029///
3030/// \param HasExplicitTemplateArgs whether any template arguments were
3031/// explicitly provided.
3032///
3033/// \param LAngleLoc the location of the left angle bracket ('<'), if
3034/// template arguments were explicitly provided.
3035///
3036/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
3037/// if any.
3038///
3039/// \param NumExplicitTemplateArgs the number of explicitly-provided template
3040/// arguments. This number may be zero even when HasExplicitTemplateArgs is
3041/// true as in, e.g., \c void sort<>(char*, char*);
3042///
3043/// \param RAngleLoc the location of the right angle bracket ('>'), if
3044/// template arguments were explicitly provided.
3045///
3046/// \param PrevDecl the set of declarations that
3047bool
3048Sema::CheckFunctionTemplateSpecialization(FunctionDecl *FD,
3049 bool HasExplicitTemplateArgs,
3050 SourceLocation LAngleLoc,
3051 const TemplateArgument *ExplicitTemplateArgs,
3052 unsigned NumExplicitTemplateArgs,
3053 SourceLocation RAngleLoc,
3054 NamedDecl *&PrevDecl) {
3055 // The set of function template specializations that could match this
3056 // explicit function template specialization.
3057 typedef llvm::SmallVector<FunctionDecl *, 8> CandidateSet;
3058 CandidateSet Candidates;
3059
3060 DeclContext *FDLookupContext = FD->getDeclContext()->getLookupContext();
3061 for (OverloadIterator Ovl(PrevDecl), OvlEnd; Ovl != OvlEnd; ++Ovl) {
3062 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(*Ovl)) {
3063 // Only consider templates found within the same semantic lookup scope as
3064 // FD.
3065 if (!FDLookupContext->Equals(Ovl->getDeclContext()->getLookupContext()))
3066 continue;
3067
3068 // C++ [temp.expl.spec]p11:
3069 // A trailing template-argument can be left unspecified in the
3070 // template-id naming an explicit function template specialization
3071 // provided it can be deduced from the function argument type.
3072 // Perform template argument deduction to determine whether we may be
3073 // specializing this template.
3074 // FIXME: It is somewhat wasteful to build
3075 TemplateDeductionInfo Info(Context);
3076 FunctionDecl *Specialization = 0;
3077 if (TemplateDeductionResult TDK
3078 = DeduceTemplateArguments(FunTmpl, HasExplicitTemplateArgs,
3079 ExplicitTemplateArgs,
3080 NumExplicitTemplateArgs,
3081 FD->getType(),
3082 Specialization,
3083 Info)) {
3084 // FIXME: Template argument deduction failed; record why it failed, so
3085 // that we can provide nifty diagnostics.
3086 (void)TDK;
3087 continue;
3088 }
3089
3090 // Record this candidate.
3091 Candidates.push_back(Specialization);
3092 }
3093 }
3094
Douglas Gregor5de279c2009-09-26 03:41:46 +00003095 // Find the most specialized function template.
3096 FunctionDecl *Specialization = getMostSpecialized(Candidates.data(),
3097 Candidates.size(),
3098 TPOC_Other,
3099 FD->getLocation(),
3100 PartialDiagnostic(diag::err_function_template_spec_no_match)
3101 << FD->getDeclName(),
3102 PartialDiagnostic(diag::err_function_template_spec_ambiguous)
3103 << FD->getDeclName() << HasExplicitTemplateArgs,
3104 PartialDiagnostic(diag::note_function_template_spec_matched));
3105 if (!Specialization)
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003106 return true;
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003107
3108 // FIXME: Check if the prior specialization has a point of instantiation.
3109 // If so, we have run afoul of C++ [temp.expl.spec]p6.
3110
Douglas Gregor54888652009-10-07 00:13:32 +00003111 // Check the scope of this explicit specialization.
3112 if (CheckTemplateSpecializationScope(*this,
3113 Specialization->getPrimaryTemplate(),
3114 Specialization, FD->getLocation(),
3115 false, TSK_ExplicitSpecialization))
3116 return true;
3117
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003118 // Mark the prior declaration as an explicit specialization, so that later
3119 // clients know that this is an explicit specialization.
3120 // FIXME: Check for prior explicit instantiations?
3121 Specialization->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
3122
3123 // Turn the given function declaration into a function template
3124 // specialization, with the template arguments from the previous
3125 // specialization.
3126 FD->setFunctionTemplateSpecialization(Context,
3127 Specialization->getPrimaryTemplate(),
3128 new (Context) TemplateArgumentList(
3129 *Specialization->getTemplateSpecializationArgs()),
3130 /*InsertPos=*/0,
3131 TSK_ExplicitSpecialization);
3132
3133 // The "previous declaration" for this function template specialization is
3134 // the prior function template specialization.
3135 PrevDecl = Specialization;
3136 return false;
3137}
3138
Douglas Gregor86d142a2009-10-08 07:24:58 +00003139/// \brief Perform semantic analysis for the given non-template member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003140/// specialization.
3141///
3142/// This routine performs all of the semantic analysis required for an
3143/// explicit member function specialization. On successful completion,
3144/// the function declaration \p FD will become a member function
3145/// specialization.
3146///
Douglas Gregor86d142a2009-10-08 07:24:58 +00003147/// \param Member the member declaration, which will be updated to become a
3148/// specialization.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003149///
3150/// \param PrevDecl the set of declarations, one of which may be specialized
3151/// by this function specialization.
3152bool
Douglas Gregor86d142a2009-10-08 07:24:58 +00003153Sema::CheckMemberSpecialization(NamedDecl *Member, NamedDecl *&PrevDecl) {
3154 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
3155
3156 // Try to find the member we are instantiating.
3157 NamedDecl *Instantiation = 0;
3158 NamedDecl *InstantiatedFrom = 0;
3159 if (!PrevDecl) {
3160 // Nowhere to look anyway.
3161 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
3162 for (OverloadIterator Ovl(PrevDecl), OvlEnd; Ovl != OvlEnd; ++Ovl) {
3163 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*Ovl)) {
3164 if (Context.hasSameType(Function->getType(), Method->getType())) {
3165 Instantiation = Method;
3166 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
3167 break;
3168 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003169 }
3170 }
Douglas Gregor86d142a2009-10-08 07:24:58 +00003171 } else if (isa<VarDecl>(Member)) {
3172 if (VarDecl *PrevVar = dyn_cast<VarDecl>(PrevDecl))
3173 if (PrevVar->isStaticDataMember()) {
3174 Instantiation = PrevDecl;
3175 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
3176 }
3177 } else if (isa<RecordDecl>(Member)) {
3178 if (CXXRecordDecl *PrevRecord = dyn_cast<CXXRecordDecl>(PrevDecl)) {
3179 Instantiation = PrevDecl;
3180 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
3181 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003182 }
3183
3184 if (!Instantiation) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00003185 // There is no previous declaration that matches. Since member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003186 // specializations are always out-of-line, the caller will complain about
3187 // this mismatch later.
3188 return false;
3189 }
3190
3191 // FIXME: Check if the prior declaration has a point of instantiation.
3192 // If so, we have run afoul of C++ [temp.expl.spec]p6.
3193
Douglas Gregor86d142a2009-10-08 07:24:58 +00003194 // Make sure that this is a specialization of a member.
3195 if (!InstantiatedFrom) {
3196 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
3197 << Member;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003198 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
3199 return true;
3200 }
3201
3202 // Check the scope of this explicit specialization.
3203 if (CheckTemplateSpecializationScope(*this,
Douglas Gregor86d142a2009-10-08 07:24:58 +00003204 InstantiatedFrom,
3205 Instantiation, Member->getLocation(),
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003206 false, TSK_ExplicitSpecialization))
3207 return true;
Douglas Gregord801b062009-10-07 23:56:10 +00003208
3209 // FIXME: Check for specialization-after-instantiation errors and such.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003210
Douglas Gregor86d142a2009-10-08 07:24:58 +00003211 // Note that this is an explicit instantiation of a member.
Douglas Gregorbbe8f462009-10-08 15:14:33 +00003212 // the original declaration to note that it is an explicit specialization
3213 // (if it was previously an implicit instantiation). This latter step
3214 // makes bookkeeping easier.
Douglas Gregor86d142a2009-10-08 07:24:58 +00003215 if (isa<FunctionDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00003216 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
3217 if (InstantiationFunction->getTemplateSpecializationKind() ==
3218 TSK_ImplicitInstantiation) {
3219 InstantiationFunction->setTemplateSpecializationKind(
3220 TSK_ExplicitSpecialization);
3221 InstantiationFunction->setLocation(Member->getLocation());
3222 }
3223
Douglas Gregor86d142a2009-10-08 07:24:58 +00003224 cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
3225 cast<CXXMethodDecl>(InstantiatedFrom),
3226 TSK_ExplicitSpecialization);
3227 } else if (isa<VarDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00003228 VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
3229 if (InstantiationVar->getTemplateSpecializationKind() ==
3230 TSK_ImplicitInstantiation) {
3231 InstantiationVar->setTemplateSpecializationKind(
3232 TSK_ExplicitSpecialization);
3233 InstantiationVar->setLocation(Member->getLocation());
3234 }
3235
Douglas Gregor86d142a2009-10-08 07:24:58 +00003236 Context.setInstantiatedFromStaticDataMember(cast<VarDecl>(Member),
3237 cast<VarDecl>(InstantiatedFrom),
3238 TSK_ExplicitSpecialization);
3239 } else {
3240 assert(isa<CXXRecordDecl>(Member) && "Only member classes remain");
Douglas Gregorbbe8f462009-10-08 15:14:33 +00003241 CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
3242 if (InstantiationClass->getTemplateSpecializationKind() ==
3243 TSK_ImplicitInstantiation) {
3244 InstantiationClass->setTemplateSpecializationKind(
3245 TSK_ExplicitSpecialization);
3246 InstantiationClass->setLocation(Member->getLocation());
3247 }
3248
Douglas Gregor86d142a2009-10-08 07:24:58 +00003249 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
Douglas Gregorbbe8f462009-10-08 15:14:33 +00003250 cast<CXXRecordDecl>(InstantiatedFrom),
3251 TSK_ExplicitSpecialization);
Douglas Gregor86d142a2009-10-08 07:24:58 +00003252 }
3253
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003254 // Save the caller the trouble of having to figure out which declaration
3255 // this specialization matches.
3256 PrevDecl = Instantiation;
3257 return false;
3258}
3259
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003260// Explicit instantiation of a class template specialization
Douglas Gregor43e75172009-09-04 06:33:52 +00003261// FIXME: Implement extern template semantics
Douglas Gregora1f49972009-05-13 00:25:59 +00003262Sema::DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00003263Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00003264 SourceLocation ExternLoc,
3265 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00003266 unsigned TagSpec,
Douglas Gregora1f49972009-05-13 00:25:59 +00003267 SourceLocation KWLoc,
3268 const CXXScopeSpec &SS,
3269 TemplateTy TemplateD,
3270 SourceLocation TemplateNameLoc,
3271 SourceLocation LAngleLoc,
3272 ASTTemplateArgsPtr TemplateArgsIn,
3273 SourceLocation *TemplateArgLocs,
3274 SourceLocation RAngleLoc,
3275 AttributeList *Attr) {
3276 // Find the class template we're specializing
3277 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump11289f42009-09-09 15:08:12 +00003278 ClassTemplateDecl *ClassTemplate
Douglas Gregora1f49972009-05-13 00:25:59 +00003279 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
3280
3281 // Check that the specialization uses the same tag kind as the
3282 // original template.
3283 TagDecl::TagKind Kind;
3284 switch (TagSpec) {
3285 default: assert(0 && "Unknown tag type!");
3286 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
3287 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
3288 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
3289 }
Douglas Gregord9034f02009-05-14 16:41:31 +00003290 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump11289f42009-09-09 15:08:12 +00003291 Kind, KWLoc,
Douglas Gregord9034f02009-05-14 16:41:31 +00003292 *ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00003293 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora1f49972009-05-13 00:25:59 +00003294 << ClassTemplate
Mike Stump11289f42009-09-09 15:08:12 +00003295 << CodeModificationHint::CreateReplacement(KWLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00003296 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00003297 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregora1f49972009-05-13 00:25:59 +00003298 diag::note_previous_use);
3299 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
3300 }
3301
Douglas Gregor54888652009-10-07 00:13:32 +00003302 TemplateSpecializationKind TSK
3303 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
3304 : TSK_ExplicitInstantiationDeclaration;
3305
Douglas Gregora1f49972009-05-13 00:25:59 +00003306 // Translate the parser's template argument list in our AST format.
3307 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
3308 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
3309
3310 // Check that the template argument list is well-formed for this
3311 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003312 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
3313 TemplateArgs.size());
Mike Stump11289f42009-09-09 15:08:12 +00003314 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
Anders Carlssondd096d82009-06-05 02:12:32 +00003315 TemplateArgs.data(), TemplateArgs.size(),
Douglas Gregore3f1f352009-07-01 00:28:38 +00003316 RAngleLoc, false, Converted))
Douglas Gregora1f49972009-05-13 00:25:59 +00003317 return true;
3318
Mike Stump11289f42009-09-09 15:08:12 +00003319 assert((Converted.structuredSize() ==
Douglas Gregora1f49972009-05-13 00:25:59 +00003320 ClassTemplate->getTemplateParameters()->size()) &&
3321 "Converted template argument list is too short!");
Mike Stump11289f42009-09-09 15:08:12 +00003322
Douglas Gregora1f49972009-05-13 00:25:59 +00003323 // Find the class template specialization declaration that
3324 // corresponds to these arguments.
3325 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00003326 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003327 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00003328 Converted.flatSize(),
3329 Context);
Douglas Gregora1f49972009-05-13 00:25:59 +00003330 void *InsertPos = 0;
3331 ClassTemplateSpecializationDecl *PrevDecl
3332 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
3333
Douglas Gregor54888652009-10-07 00:13:32 +00003334 // C++0x [temp.explicit]p2:
3335 // [...] An explicit instantiation shall appear in an enclosing
3336 // namespace of its template. [...]
3337 //
3338 // This is C++ DR 275.
3339 if (CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
3340 TemplateNameLoc, false,
3341 TSK))
3342 return true;
3343
Douglas Gregora1f49972009-05-13 00:25:59 +00003344 ClassTemplateSpecializationDecl *Specialization = 0;
3345
Douglas Gregorf61eca92009-05-13 18:28:20 +00003346 bool SpecializationRequiresInstantiation = true;
Douglas Gregora1f49972009-05-13 00:25:59 +00003347 if (PrevDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00003348 if (PrevDecl->getSpecializationKind()
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003349 == TSK_ExplicitInstantiationDefinition) {
Douglas Gregora1f49972009-05-13 00:25:59 +00003350 // This particular specialization has already been declared or
3351 // instantiated. We cannot explicitly instantiate it.
Douglas Gregorf61eca92009-05-13 18:28:20 +00003352 Diag(TemplateNameLoc, diag::err_explicit_instantiation_duplicate)
3353 << Context.getTypeDeclType(PrevDecl);
Mike Stump11289f42009-09-09 15:08:12 +00003354 Diag(PrevDecl->getLocation(),
Douglas Gregorf61eca92009-05-13 18:28:20 +00003355 diag::note_previous_explicit_instantiation);
Douglas Gregora1f49972009-05-13 00:25:59 +00003356 return DeclPtrTy::make(PrevDecl);
3357 }
3358
Douglas Gregorf61eca92009-05-13 18:28:20 +00003359 if (PrevDecl->getSpecializationKind() == TSK_ExplicitSpecialization) {
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003360 // C++ DR 259, C++0x [temp.explicit]p4:
Douglas Gregorf61eca92009-05-13 18:28:20 +00003361 // For a given set of template parameters, if an explicit
3362 // instantiation of a template appears after a declaration of
3363 // an explicit specialization for that template, the explicit
3364 // instantiation has no effect.
3365 if (!getLangOptions().CPlusPlus0x) {
Mike Stump11289f42009-09-09 15:08:12 +00003366 Diag(TemplateNameLoc,
Douglas Gregorf61eca92009-05-13 18:28:20 +00003367 diag::ext_explicit_instantiation_after_specialization)
3368 << Context.getTypeDeclType(PrevDecl);
Mike Stump11289f42009-09-09 15:08:12 +00003369 Diag(PrevDecl->getLocation(),
Douglas Gregorf61eca92009-05-13 18:28:20 +00003370 diag::note_previous_template_specialization);
3371 }
3372
3373 // Create a new class template specialization declaration node
3374 // for this explicit specialization. This node is only used to
3375 // record the existence of this explicit instantiation for
3376 // accurate reproduction of the source code; we don't actually
3377 // use it for anything, since it is semantically irrelevant.
3378 Specialization
Mike Stump11289f42009-09-09 15:08:12 +00003379 = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregorf61eca92009-05-13 18:28:20 +00003380 ClassTemplate->getDeclContext(),
3381 TemplateNameLoc,
3382 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003383 Converted, 0);
Douglas Gregorf61eca92009-05-13 18:28:20 +00003384 Specialization->setLexicalDeclContext(CurContext);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003385 CurContext->addDecl(Specialization);
Douglas Gregor4aa04b12009-09-11 21:19:12 +00003386 return DeclPtrTy::make(PrevDecl);
Douglas Gregorf61eca92009-05-13 18:28:20 +00003387 }
3388
3389 // If we have already (implicitly) instantiated this
3390 // specialization, there is less work to do.
3391 if (PrevDecl->getSpecializationKind() == TSK_ImplicitInstantiation)
3392 SpecializationRequiresInstantiation = false;
3393
Douglas Gregor4aa04b12009-09-11 21:19:12 +00003394 if (PrevDecl->getSpecializationKind() == TSK_ImplicitInstantiation ||
3395 PrevDecl->getSpecializationKind() == TSK_Undeclared) {
3396 // Since the only prior class template specialization with these
3397 // arguments was referenced but not declared, reuse that
3398 // declaration node as our own, updating its source location to
3399 // reflect our new declaration.
3400 Specialization = PrevDecl;
3401 Specialization->setLocation(TemplateNameLoc);
3402 PrevDecl = 0;
3403 }
3404 }
3405
3406 if (!Specialization) {
Douglas Gregora1f49972009-05-13 00:25:59 +00003407 // Create a new class template specialization declaration node for
3408 // this explicit specialization.
3409 Specialization
Mike Stump11289f42009-09-09 15:08:12 +00003410 = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregora1f49972009-05-13 00:25:59 +00003411 ClassTemplate->getDeclContext(),
3412 TemplateNameLoc,
3413 ClassTemplate,
Douglas Gregor4aa04b12009-09-11 21:19:12 +00003414 Converted, PrevDecl);
Douglas Gregora1f49972009-05-13 00:25:59 +00003415
Douglas Gregor4aa04b12009-09-11 21:19:12 +00003416 if (PrevDecl) {
3417 // Remove the previous declaration from the folding set, since we want
3418 // to introduce a new declaration.
3419 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
3420 ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
3421 }
3422
3423 // Insert the new specialization.
3424 ClassTemplate->getSpecializations().InsertNode(Specialization, InsertPos);
Douglas Gregora1f49972009-05-13 00:25:59 +00003425 }
3426
3427 // Build the fully-sugared type for this explicit instantiation as
3428 // the user wrote in the explicit instantiation itself. This means
3429 // that we'll pretty-print the type retrieved from the
3430 // specialization's declaration the way that the user actually wrote
3431 // the explicit instantiation, rather than formatting the name based
3432 // on the "canonical" representation used to store the template
3433 // arguments in the specialization.
Mike Stump11289f42009-09-09 15:08:12 +00003434 QualType WrittenTy
3435 = Context.getTemplateSpecializationType(Name,
Anders Carlsson03c9e872009-06-05 02:45:24 +00003436 TemplateArgs.data(),
Douglas Gregora1f49972009-05-13 00:25:59 +00003437 TemplateArgs.size(),
3438 Context.getTypeDeclType(Specialization));
3439 Specialization->setTypeAsWritten(WrittenTy);
3440 TemplateArgsIn.release();
3441
3442 // Add the explicit instantiation into its lexical context. However,
3443 // since explicit instantiations are never found by name lookup, we
3444 // just put it into the declaration context directly.
3445 Specialization->setLexicalDeclContext(CurContext);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003446 CurContext->addDecl(Specialization);
Douglas Gregora1f49972009-05-13 00:25:59 +00003447
John McCall1806c272009-09-11 07:25:08 +00003448 Specialization->setPointOfInstantiation(TemplateNameLoc);
3449
Douglas Gregora1f49972009-05-13 00:25:59 +00003450 // C++ [temp.explicit]p3:
Douglas Gregora1f49972009-05-13 00:25:59 +00003451 // A definition of a class template or class member template
3452 // shall be in scope at the point of the explicit instantiation of
3453 // the class template or class member template.
3454 //
3455 // This check comes when we actually try to perform the
3456 // instantiation.
Douglas Gregor67da0d92009-05-15 17:59:04 +00003457 if (SpecializationRequiresInstantiation)
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003458 InstantiateClassTemplateSpecialization(Specialization, TSK);
Douglas Gregor85673582009-05-18 17:01:57 +00003459 else // Instantiate the members of this class template specialization.
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003460 InstantiateClassTemplateSpecializationMembers(TemplateLoc, Specialization,
3461 TSK);
Douglas Gregora1f49972009-05-13 00:25:59 +00003462
3463 return DeclPtrTy::make(Specialization);
3464}
3465
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003466// Explicit instantiation of a member class of a class template.
3467Sema::DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00003468Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00003469 SourceLocation ExternLoc,
3470 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00003471 unsigned TagSpec,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003472 SourceLocation KWLoc,
3473 const CXXScopeSpec &SS,
3474 IdentifierInfo *Name,
3475 SourceLocation NameLoc,
3476 AttributeList *Attr) {
3477
Douglas Gregord6ab8742009-05-28 23:31:59 +00003478 bool Owned = false;
John McCall7f41d982009-09-11 04:59:25 +00003479 bool IsDependent = false;
John McCall9bb74a52009-07-31 02:45:11 +00003480 DeclPtrTy TagD = ActOnTag(S, TagSpec, Action::TUK_Reference,
Douglas Gregore93e46c2009-07-22 23:48:44 +00003481 KWLoc, SS, Name, NameLoc, Attr, AS_none,
John McCall7f41d982009-09-11 04:59:25 +00003482 MultiTemplateParamsArg(*this, 0, 0),
3483 Owned, IsDependent);
3484 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
3485
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003486 if (!TagD)
3487 return true;
3488
3489 TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
3490 if (Tag->isEnum()) {
3491 Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
3492 << Context.getTypeDeclType(Tag);
3493 return true;
3494 }
3495
Douglas Gregorb8006faf2009-05-27 17:30:49 +00003496 if (Tag->isInvalidDecl())
3497 return true;
3498
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003499 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
3500 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
3501 if (!Pattern) {
3502 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
3503 << Context.getTypeDeclType(Record);
3504 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
3505 return true;
3506 }
3507
3508 // C++0x [temp.explicit]p2:
3509 // [...] An explicit instantiation shall appear in an enclosing
3510 // namespace of its template. [...]
3511 //
3512 // This is C++ DR 275.
3513 if (getLangOptions().CPlusPlus0x) {
Mike Stump87c57ac2009-05-16 07:39:55 +00003514 // FIXME: In C++98, we would like to turn these errors into warnings,
3515 // dependent on a -Wc++0x flag.
Mike Stump11289f42009-09-09 15:08:12 +00003516 DeclContext *PatternContext
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003517 = Pattern->getDeclContext()->getEnclosingNamespaceContext();
3518 if (!CurContext->Encloses(PatternContext)) {
3519 Diag(TemplateLoc, diag::err_explicit_instantiation_out_of_scope)
3520 << Record << cast<NamedDecl>(PatternContext) << SS.getRange();
3521 Diag(Pattern->getLocation(), diag::note_previous_declaration);
3522 }
3523 }
3524
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003525 TemplateSpecializationKind TSK
Mike Stump11289f42009-09-09 15:08:12 +00003526 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003527 : TSK_ExplicitInstantiationDeclaration;
Mike Stump11289f42009-09-09 15:08:12 +00003528
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003529 if (!Record->getDefinition(Context)) {
3530 // If the class has a definition, instantiate it (and all of its
3531 // members, recursively).
3532 Pattern = cast_or_null<CXXRecordDecl>(Pattern->getDefinition(Context));
Mike Stump11289f42009-09-09 15:08:12 +00003533 if (Pattern && InstantiateClass(TemplateLoc, Record, Pattern,
Douglas Gregorb4850462009-05-14 23:26:13 +00003534 getTemplateInstantiationArgs(Record),
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003535 TSK))
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003536 return true;
John McCall76d824f2009-08-25 22:02:44 +00003537 } else // Instantiate all of the members of the class.
Mike Stump11289f42009-09-09 15:08:12 +00003538 InstantiateClassMembers(TemplateLoc, Record,
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003539 getTemplateInstantiationArgs(Record), TSK);
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003540
Mike Stump87c57ac2009-05-16 07:39:55 +00003541 // FIXME: We don't have any representation for explicit instantiations of
3542 // member classes. Such a representation is not needed for compilation, but it
3543 // should be available for clients that want to see all of the declarations in
3544 // the source code.
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003545 return TagD;
3546}
3547
Douglas Gregor450f00842009-09-25 18:43:00 +00003548Sema::DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
3549 SourceLocation ExternLoc,
3550 SourceLocation TemplateLoc,
3551 Declarator &D) {
3552 // Explicit instantiations always require a name.
3553 DeclarationName Name = GetNameForDeclarator(D);
3554 if (!Name) {
3555 if (!D.isInvalidType())
3556 Diag(D.getDeclSpec().getSourceRange().getBegin(),
3557 diag::err_explicit_instantiation_requires_name)
3558 << D.getDeclSpec().getSourceRange()
3559 << D.getSourceRange();
3560
3561 return true;
3562 }
3563
3564 // The scope passed in may not be a decl scope. Zip up the scope tree until
3565 // we find one that is.
3566 while ((S->getFlags() & Scope::DeclScope) == 0 ||
3567 (S->getFlags() & Scope::TemplateParamScope) != 0)
3568 S = S->getParent();
3569
3570 // Determine the type of the declaration.
3571 QualType R = GetTypeForDeclarator(D, S, 0);
3572 if (R.isNull())
3573 return true;
3574
3575 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
3576 // Cannot explicitly instantiate a typedef.
3577 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
3578 << Name;
3579 return true;
3580 }
3581
3582 // Determine what kind of explicit instantiation we have.
3583 TemplateSpecializationKind TSK
3584 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
3585 : TSK_ExplicitInstantiationDeclaration;
3586
John McCall9f3059a2009-10-09 21:13:30 +00003587 LookupResult Previous;
3588 LookupParsedName(Previous, S, &D.getCXXScopeSpec(),
3589 Name, LookupOrdinaryName);
Douglas Gregor450f00842009-09-25 18:43:00 +00003590
3591 if (!R->isFunctionType()) {
3592 // C++ [temp.explicit]p1:
3593 // A [...] static data member of a class template can be explicitly
3594 // instantiated from the member definition associated with its class
3595 // template.
3596 if (Previous.isAmbiguous()) {
3597 return DiagnoseAmbiguousLookup(Previous, Name, D.getIdentifierLoc(),
3598 D.getSourceRange());
3599 }
3600
John McCall9f3059a2009-10-09 21:13:30 +00003601 VarDecl *Prev = dyn_cast_or_null<VarDecl>(
3602 Previous.getAsSingleDecl(Context));
Douglas Gregor450f00842009-09-25 18:43:00 +00003603 if (!Prev || !Prev->isStaticDataMember()) {
3604 // We expect to see a data data member here.
3605 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
3606 << Name;
3607 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
3608 P != PEnd; ++P)
John McCall9f3059a2009-10-09 21:13:30 +00003609 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor450f00842009-09-25 18:43:00 +00003610 return true;
3611 }
3612
3613 if (!Prev->getInstantiatedFromStaticDataMember()) {
3614 // FIXME: Check for explicit specialization?
3615 Diag(D.getIdentifierLoc(),
3616 diag::err_explicit_instantiation_data_member_not_instantiated)
3617 << Prev;
3618 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
3619 // FIXME: Can we provide a note showing where this was declared?
3620 return true;
3621 }
3622
3623 // Instantiate static data member.
Douglas Gregor86d142a2009-10-08 07:24:58 +00003624 // FIXME: Check for prior specializations and such.
3625 Prev->setTemplateSpecializationKind(TSK);
Douglas Gregor450f00842009-09-25 18:43:00 +00003626 if (TSK == TSK_ExplicitInstantiationDefinition)
3627 InstantiateStaticDataMemberDefinition(D.getIdentifierLoc(), Prev, false);
3628
3629 // FIXME: Create an ExplicitInstantiation node?
3630 return DeclPtrTy();
3631 }
3632
Douglas Gregor0e876e02009-09-25 23:53:26 +00003633 // If the declarator is a template-id, translate the parser's template
3634 // argument list into our AST format.
Douglas Gregord90fd522009-09-25 21:45:23 +00003635 bool HasExplicitTemplateArgs = false;
3636 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
3637 if (D.getKind() == Declarator::DK_TemplateId) {
3638 TemplateIdAnnotation *TemplateId = D.getTemplateId();
3639 ASTTemplateArgsPtr TemplateArgsPtr(*this,
3640 TemplateId->getTemplateArgs(),
3641 TemplateId->getTemplateArgIsType(),
3642 TemplateId->NumArgs);
3643 translateTemplateArguments(TemplateArgsPtr,
3644 TemplateId->getTemplateArgLocations(),
3645 TemplateArgs);
3646 HasExplicitTemplateArgs = true;
Douglas Gregorf343fd82009-10-01 23:51:25 +00003647 TemplateArgsPtr.release();
Douglas Gregord90fd522009-09-25 21:45:23 +00003648 }
Douglas Gregor0e876e02009-09-25 23:53:26 +00003649
Douglas Gregor450f00842009-09-25 18:43:00 +00003650 // C++ [temp.explicit]p1:
3651 // A [...] function [...] can be explicitly instantiated from its template.
3652 // A member function [...] of a class template can be explicitly
3653 // instantiated from the member definition associated with its class
3654 // template.
Douglas Gregor450f00842009-09-25 18:43:00 +00003655 llvm::SmallVector<FunctionDecl *, 8> Matches;
3656 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
3657 P != PEnd; ++P) {
3658 NamedDecl *Prev = *P;
Douglas Gregord90fd522009-09-25 21:45:23 +00003659 if (!HasExplicitTemplateArgs) {
3660 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
3661 if (Context.hasSameUnqualifiedType(Method->getType(), R)) {
3662 Matches.clear();
3663 Matches.push_back(Method);
3664 break;
3665 }
Douglas Gregor450f00842009-09-25 18:43:00 +00003666 }
3667 }
3668
3669 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
3670 if (!FunTmpl)
3671 continue;
3672
3673 TemplateDeductionInfo Info(Context);
3674 FunctionDecl *Specialization = 0;
3675 if (TemplateDeductionResult TDK
Douglas Gregord90fd522009-09-25 21:45:23 +00003676 = DeduceTemplateArguments(FunTmpl, HasExplicitTemplateArgs,
3677 TemplateArgs.data(), TemplateArgs.size(),
Douglas Gregor450f00842009-09-25 18:43:00 +00003678 R, Specialization, Info)) {
3679 // FIXME: Keep track of almost-matches?
3680 (void)TDK;
3681 continue;
3682 }
3683
3684 Matches.push_back(Specialization);
3685 }
3686
3687 // Find the most specialized function template specialization.
3688 FunctionDecl *Specialization
3689 = getMostSpecialized(Matches.data(), Matches.size(), TPOC_Other,
3690 D.getIdentifierLoc(),
3691 PartialDiagnostic(diag::err_explicit_instantiation_not_known) << Name,
3692 PartialDiagnostic(diag::err_explicit_instantiation_ambiguous) << Name,
3693 PartialDiagnostic(diag::note_explicit_instantiation_candidate));
3694
3695 if (!Specialization)
3696 return true;
3697
3698 switch (Specialization->getTemplateSpecializationKind()) {
3699 case TSK_Undeclared:
3700 Diag(D.getIdentifierLoc(),
3701 diag::err_explicit_instantiation_member_function_not_instantiated)
3702 << Specialization
3703 << (Specialization->getTemplateSpecializationKind() ==
3704 TSK_ExplicitSpecialization);
3705 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
3706 return true;
3707
3708 case TSK_ExplicitSpecialization:
3709 // C++ [temp.explicit]p4:
3710 // For a given set of template parameters, if an explicit instantiation
3711 // of a template appears after a declaration of an explicit
3712 // specialization for that template, the explicit instantiation has no
3713 // effect.
3714 break;
3715
3716 case TSK_ExplicitInstantiationDefinition:
3717 // FIXME: Check that we aren't trying to perform an explicit instantiation
3718 // declaration now.
3719 // Fall through
3720
3721 case TSK_ImplicitInstantiation:
3722 case TSK_ExplicitInstantiationDeclaration:
3723 // Instantiate the function, if this is an explicit instantiation
3724 // definition.
3725 if (TSK == TSK_ExplicitInstantiationDefinition)
3726 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization,
3727 false);
3728
Douglas Gregor450f00842009-09-25 18:43:00 +00003729 Specialization->setTemplateSpecializationKind(TSK);
3730 break;
3731 }
3732
3733 // FIXME: Create some kind of ExplicitInstantiationDecl here.
3734 return DeclPtrTy();
3735}
3736
Douglas Gregor333489b2009-03-27 23:10:48 +00003737Sema::TypeResult
John McCall7f41d982009-09-11 04:59:25 +00003738Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
3739 const CXXScopeSpec &SS, IdentifierInfo *Name,
3740 SourceLocation TagLoc, SourceLocation NameLoc) {
3741 // This has to hold, because SS is expected to be defined.
3742 assert(Name && "Expected a name in a dependent tag");
3743
3744 NestedNameSpecifier *NNS
3745 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3746 if (!NNS)
3747 return true;
3748
3749 QualType T = CheckTypenameType(NNS, *Name, SourceRange(TagLoc, NameLoc));
3750 if (T.isNull())
3751 return true;
3752
3753 TagDecl::TagKind TagKind = TagDecl::getTagKindForTypeSpec(TagSpec);
3754 QualType ElabType = Context.getElaboratedType(T, TagKind);
3755
3756 return ElabType.getAsOpaquePtr();
3757}
3758
3759Sema::TypeResult
Douglas Gregor333489b2009-03-27 23:10:48 +00003760Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
3761 const IdentifierInfo &II, SourceLocation IdLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00003762 NestedNameSpecifier *NNS
Douglas Gregor333489b2009-03-27 23:10:48 +00003763 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3764 if (!NNS)
3765 return true;
3766
3767 QualType T = CheckTypenameType(NNS, II, SourceRange(TypenameLoc, IdLoc));
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00003768 if (T.isNull())
3769 return true;
Douglas Gregor333489b2009-03-27 23:10:48 +00003770 return T.getAsOpaquePtr();
3771}
3772
Douglas Gregordce2b622009-04-01 00:28:59 +00003773Sema::TypeResult
3774Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
3775 SourceLocation TemplateLoc, TypeTy *Ty) {
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00003776 QualType T = GetTypeFromParser(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00003777 NestedNameSpecifier *NNS
Douglas Gregordce2b622009-04-01 00:28:59 +00003778 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Mike Stump11289f42009-09-09 15:08:12 +00003779 const TemplateSpecializationType *TemplateId
John McCall9dd450b2009-09-21 23:43:11 +00003780 = T->getAs<TemplateSpecializationType>();
Douglas Gregordce2b622009-04-01 00:28:59 +00003781 assert(TemplateId && "Expected a template specialization type");
3782
Douglas Gregor12bbfe12009-09-02 13:05:45 +00003783 if (computeDeclContext(SS, false)) {
3784 // If we can compute a declaration context, then the "typename"
3785 // keyword was superfluous. Just build a QualifiedNameType to keep
3786 // track of the nested-name-specifier.
Mike Stump11289f42009-09-09 15:08:12 +00003787
Douglas Gregor12bbfe12009-09-02 13:05:45 +00003788 // FIXME: Note that the QualifiedNameType had the "typename" keyword!
3789 return Context.getQualifiedNameType(NNS, T).getAsOpaquePtr();
3790 }
Mike Stump11289f42009-09-09 15:08:12 +00003791
Douglas Gregor12bbfe12009-09-02 13:05:45 +00003792 return Context.getTypenameType(NNS, TemplateId).getAsOpaquePtr();
Douglas Gregordce2b622009-04-01 00:28:59 +00003793}
3794
Douglas Gregor333489b2009-03-27 23:10:48 +00003795/// \brief Build the type that describes a C++ typename specifier,
3796/// e.g., "typename T::type".
3797QualType
3798Sema::CheckTypenameType(NestedNameSpecifier *NNS, const IdentifierInfo &II,
3799 SourceRange Range) {
Douglas Gregorc9f9b862009-05-11 19:58:34 +00003800 CXXRecordDecl *CurrentInstantiation = 0;
3801 if (NNS->isDependent()) {
3802 CurrentInstantiation = getCurrentInstantiationOf(NNS);
Douglas Gregor333489b2009-03-27 23:10:48 +00003803
Douglas Gregorc9f9b862009-05-11 19:58:34 +00003804 // If the nested-name-specifier does not refer to the current
3805 // instantiation, then build a typename type.
3806 if (!CurrentInstantiation)
3807 return Context.getTypenameType(NNS, &II);
Mike Stump11289f42009-09-09 15:08:12 +00003808
Douglas Gregorc707da62009-09-02 13:12:51 +00003809 // The nested-name-specifier refers to the current instantiation, so the
3810 // "typename" keyword itself is superfluous. In C++03, the program is
Mike Stump11289f42009-09-09 15:08:12 +00003811 // actually ill-formed. However, DR 382 (in C++0x CD1) allows such
Douglas Gregorc707da62009-09-02 13:12:51 +00003812 // extraneous "typename" keywords, and we retroactively apply this DR to
3813 // C++03 code.
Douglas Gregorc9f9b862009-05-11 19:58:34 +00003814 }
Douglas Gregor333489b2009-03-27 23:10:48 +00003815
Douglas Gregorc9f9b862009-05-11 19:58:34 +00003816 DeclContext *Ctx = 0;
3817
3818 if (CurrentInstantiation)
3819 Ctx = CurrentInstantiation;
3820 else {
3821 CXXScopeSpec SS;
3822 SS.setScopeRep(NNS);
3823 SS.setRange(Range);
3824 if (RequireCompleteDeclContext(SS))
3825 return QualType();
3826
3827 Ctx = computeDeclContext(SS);
3828 }
Douglas Gregor333489b2009-03-27 23:10:48 +00003829 assert(Ctx && "No declaration context?");
3830
3831 DeclarationName Name(&II);
John McCall9f3059a2009-10-09 21:13:30 +00003832 LookupResult Result;
3833 LookupQualifiedName(Result, Ctx, Name, LookupOrdinaryName, false);
Douglas Gregor333489b2009-03-27 23:10:48 +00003834 unsigned DiagID = 0;
3835 Decl *Referenced = 0;
3836 switch (Result.getKind()) {
3837 case LookupResult::NotFound:
3838 if (Ctx->isTranslationUnit())
3839 DiagID = diag::err_typename_nested_not_found_global;
3840 else
3841 DiagID = diag::err_typename_nested_not_found;
3842 break;
3843
3844 case LookupResult::Found:
John McCall9f3059a2009-10-09 21:13:30 +00003845 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
Douglas Gregor333489b2009-03-27 23:10:48 +00003846 // We found a type. Build a QualifiedNameType, since the
3847 // typename-specifier was just sugar. FIXME: Tell
3848 // QualifiedNameType that it has a "typename" prefix.
3849 return Context.getQualifiedNameType(NNS, Context.getTypeDeclType(Type));
3850 }
3851
3852 DiagID = diag::err_typename_nested_not_type;
John McCall9f3059a2009-10-09 21:13:30 +00003853 Referenced = Result.getFoundDecl();
Douglas Gregor333489b2009-03-27 23:10:48 +00003854 break;
3855
3856 case LookupResult::FoundOverloaded:
3857 DiagID = diag::err_typename_nested_not_type;
3858 Referenced = *Result.begin();
3859 break;
3860
John McCall6538c932009-10-10 05:48:19 +00003861 case LookupResult::Ambiguous:
Douglas Gregor333489b2009-03-27 23:10:48 +00003862 DiagnoseAmbiguousLookup(Result, Name, Range.getEnd(), Range);
3863 return QualType();
3864 }
3865
3866 // If we get here, it's because name lookup did not find a
3867 // type. Emit an appropriate diagnostic and return an error.
3868 if (NamedDecl *NamedCtx = dyn_cast<NamedDecl>(Ctx))
3869 Diag(Range.getEnd(), DiagID) << Range << Name << NamedCtx;
3870 else
3871 Diag(Range.getEnd(), DiagID) << Range << Name;
3872 if (Referenced)
3873 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
3874 << Name;
3875 return QualType();
3876}
Douglas Gregor15acfb92009-08-06 16:20:37 +00003877
3878namespace {
3879 // See Sema::RebuildTypeInCurrentInstantiation
Mike Stump11289f42009-09-09 15:08:12 +00003880 class VISIBILITY_HIDDEN CurrentInstantiationRebuilder
3881 : public TreeTransform<CurrentInstantiationRebuilder> {
Douglas Gregor15acfb92009-08-06 16:20:37 +00003882 SourceLocation Loc;
3883 DeclarationName Entity;
Mike Stump11289f42009-09-09 15:08:12 +00003884
Douglas Gregor15acfb92009-08-06 16:20:37 +00003885 public:
Mike Stump11289f42009-09-09 15:08:12 +00003886 CurrentInstantiationRebuilder(Sema &SemaRef,
Douglas Gregor15acfb92009-08-06 16:20:37 +00003887 SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00003888 DeclarationName Entity)
3889 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
Douglas Gregor15acfb92009-08-06 16:20:37 +00003890 Loc(Loc), Entity(Entity) { }
Mike Stump11289f42009-09-09 15:08:12 +00003891
3892 /// \brief Determine whether the given type \p T has already been
Douglas Gregor15acfb92009-08-06 16:20:37 +00003893 /// transformed.
3894 ///
3895 /// For the purposes of type reconstruction, a type has already been
3896 /// transformed if it is NULL or if it is not dependent.
3897 bool AlreadyTransformed(QualType T) {
3898 return T.isNull() || !T->isDependentType();
3899 }
Mike Stump11289f42009-09-09 15:08:12 +00003900
3901 /// \brief Returns the location of the entity whose type is being
Douglas Gregor15acfb92009-08-06 16:20:37 +00003902 /// rebuilt.
3903 SourceLocation getBaseLocation() { return Loc; }
Mike Stump11289f42009-09-09 15:08:12 +00003904
Douglas Gregor15acfb92009-08-06 16:20:37 +00003905 /// \brief Returns the name of the entity whose type is being rebuilt.
3906 DeclarationName getBaseEntity() { return Entity; }
Mike Stump11289f42009-09-09 15:08:12 +00003907
Douglas Gregor15acfb92009-08-06 16:20:37 +00003908 /// \brief Transforms an expression by returning the expression itself
3909 /// (an identity function).
3910 ///
3911 /// FIXME: This is completely unsafe; we will need to actually clone the
3912 /// expressions.
3913 Sema::OwningExprResult TransformExpr(Expr *E) {
3914 return getSema().Owned(E);
3915 }
Mike Stump11289f42009-09-09 15:08:12 +00003916
Douglas Gregor15acfb92009-08-06 16:20:37 +00003917 /// \brief Transforms a typename type by determining whether the type now
3918 /// refers to a member of the current instantiation, and then
3919 /// type-checking and building a QualifiedNameType (when possible).
3920 QualType TransformTypenameType(const TypenameType *T);
3921 };
3922}
3923
Mike Stump11289f42009-09-09 15:08:12 +00003924QualType
Douglas Gregor15acfb92009-08-06 16:20:37 +00003925CurrentInstantiationRebuilder::TransformTypenameType(const TypenameType *T) {
3926 NestedNameSpecifier *NNS
3927 = TransformNestedNameSpecifier(T->getQualifier(),
3928 /*FIXME:*/SourceRange(getBaseLocation()));
3929 if (!NNS)
3930 return QualType();
3931
3932 // If the nested-name-specifier did not change, and we cannot compute the
3933 // context corresponding to the nested-name-specifier, then this
3934 // typename type will not change; exit early.
3935 CXXScopeSpec SS;
3936 SS.setRange(SourceRange(getBaseLocation()));
3937 SS.setScopeRep(NNS);
3938 if (NNS == T->getQualifier() && getSema().computeDeclContext(SS) == 0)
3939 return QualType(T, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003940
3941 // Rebuild the typename type, which will probably turn into a
Douglas Gregor15acfb92009-08-06 16:20:37 +00003942 // QualifiedNameType.
3943 if (const TemplateSpecializationType *TemplateId = T->getTemplateId()) {
Mike Stump11289f42009-09-09 15:08:12 +00003944 QualType NewTemplateId
Douglas Gregor15acfb92009-08-06 16:20:37 +00003945 = TransformType(QualType(TemplateId, 0));
3946 if (NewTemplateId.isNull())
3947 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00003948
Douglas Gregor15acfb92009-08-06 16:20:37 +00003949 if (NNS == T->getQualifier() &&
3950 NewTemplateId == QualType(TemplateId, 0))
3951 return QualType(T, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003952
Douglas Gregor15acfb92009-08-06 16:20:37 +00003953 return getDerived().RebuildTypenameType(NNS, NewTemplateId);
3954 }
Mike Stump11289f42009-09-09 15:08:12 +00003955
Douglas Gregor15acfb92009-08-06 16:20:37 +00003956 return getDerived().RebuildTypenameType(NNS, T->getIdentifier());
3957}
3958
3959/// \brief Rebuilds a type within the context of the current instantiation.
3960///
Mike Stump11289f42009-09-09 15:08:12 +00003961/// The type \p T is part of the type of an out-of-line member definition of
Douglas Gregor15acfb92009-08-06 16:20:37 +00003962/// a class template (or class template partial specialization) that was parsed
Mike Stump11289f42009-09-09 15:08:12 +00003963/// and constructed before we entered the scope of the class template (or
Douglas Gregor15acfb92009-08-06 16:20:37 +00003964/// partial specialization thereof). This routine will rebuild that type now
3965/// that we have entered the declarator's scope, which may produce different
3966/// canonical types, e.g.,
3967///
3968/// \code
3969/// template<typename T>
3970/// struct X {
3971/// typedef T* pointer;
3972/// pointer data();
3973/// };
3974///
3975/// template<typename T>
3976/// typename X<T>::pointer X<T>::data() { ... }
3977/// \endcode
3978///
3979/// Here, the type "typename X<T>::pointer" will be created as a TypenameType,
3980/// since we do not know that we can look into X<T> when we parsed the type.
3981/// This function will rebuild the type, performing the lookup of "pointer"
3982/// in X<T> and returning a QualifiedNameType whose canonical type is the same
3983/// as the canonical type of T*, allowing the return types of the out-of-line
3984/// definition and the declaration to match.
3985QualType Sema::RebuildTypeInCurrentInstantiation(QualType T, SourceLocation Loc,
3986 DeclarationName Name) {
3987 if (T.isNull() || !T->isDependentType())
3988 return T;
Mike Stump11289f42009-09-09 15:08:12 +00003989
Douglas Gregor15acfb92009-08-06 16:20:37 +00003990 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
3991 return Rebuilder.TransformType(T);
Benjamin Kramer854d7de2009-08-11 22:33:06 +00003992}
Douglas Gregorbe999392009-09-15 16:23:51 +00003993
3994/// \brief Produces a formatted string that describes the binding of
3995/// template parameters to template arguments.
3996std::string
3997Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
3998 const TemplateArgumentList &Args) {
3999 std::string Result;
4000
4001 if (!Params || Params->size() == 0)
4002 return Result;
4003
4004 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
4005 if (I == 0)
4006 Result += "[with ";
4007 else
4008 Result += ", ";
4009
4010 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
4011 Result += Id->getName();
4012 } else {
4013 Result += '$';
4014 Result += llvm::utostr(I);
4015 }
4016
4017 Result += " = ";
4018
4019 switch (Args[I].getKind()) {
4020 case TemplateArgument::Null:
4021 Result += "<no value>";
4022 break;
4023
4024 case TemplateArgument::Type: {
4025 std::string TypeStr;
4026 Args[I].getAsType().getAsStringInternal(TypeStr,
4027 Context.PrintingPolicy);
4028 Result += TypeStr;
4029 break;
4030 }
4031
4032 case TemplateArgument::Declaration: {
4033 bool Unnamed = true;
4034 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(Args[I].getAsDecl())) {
4035 if (ND->getDeclName()) {
4036 Unnamed = false;
4037 Result += ND->getNameAsString();
4038 }
4039 }
4040
4041 if (Unnamed) {
4042 Result += "<anonymous>";
4043 }
4044 break;
4045 }
4046
4047 case TemplateArgument::Integral: {
4048 Result += Args[I].getAsIntegral()->toString(10);
4049 break;
4050 }
4051
4052 case TemplateArgument::Expression: {
4053 assert(false && "No expressions in deduced template arguments!");
4054 Result += "<expression>";
4055 break;
4056 }
4057
4058 case TemplateArgument::Pack:
4059 // FIXME: Format template argument packs
4060 Result += "<template argument pack>";
4061 break;
4062 }
4063 }
4064
4065 Result += ']';
4066 return Result;
4067}