blob: 36a158d3cdeda1a3d081e7e15a3d82c3efcd3304 [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()) {
Douglas Gregor568a0712009-10-14 17:30:58 +000048 Record = cast<CXXRecordDecl>(Record->getDeclContext());
Douglas Gregorb7bfe792009-09-02 22:59:36 +000049 if (Record->getDescribedClassTemplate())
50 return Record->getDescribedClassTemplate();
51
52 if (ClassTemplateSpecializationDecl *Spec
53 = dyn_cast<ClassTemplateSpecializationDecl>(Record))
54 return Spec->getSpecializedTemplate();
55 }
Mike 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()) {
Douglas Gregoref06ccf2009-10-12 23:11:44 +0000577 if (RequireCompleteDeclContext(SS))
578 return true;
579
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000580 SemanticContext = computeDeclContext(SS, true);
581 if (!SemanticContext) {
582 // FIXME: Produce a reasonable diagnostic here
583 return true;
584 }
Mike Stump11289f42009-09-09 15:08:12 +0000585
John McCall9f3059a2009-10-09 21:13:30 +0000586 LookupQualifiedName(Previous, SemanticContext, Name, LookupOrdinaryName,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000587 true);
588 } else {
589 SemanticContext = CurContext;
John McCall9f3059a2009-10-09 21:13:30 +0000590 LookupName(Previous, S, Name, LookupOrdinaryName, true);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000591 }
Mike Stump11289f42009-09-09 15:08:12 +0000592
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000593 assert(!Previous.isAmbiguous() && "Ambiguity in class template redecl?");
594 NamedDecl *PrevDecl = 0;
595 if (Previous.begin() != Previous.end())
596 PrevDecl = *Previous.begin();
597
Douglas Gregor9acb6902009-09-26 07:05:09 +0000598 if (PrevDecl && TUK == TUK_Friend) {
599 // C++ [namespace.memdef]p3:
600 // [...] When looking for a prior declaration of a class or a function
601 // declared as a friend, and when the name of the friend class or
602 // function is neither a qualified name nor a template-id, scopes outside
603 // the innermost enclosing namespace scope are not considered.
604 DeclContext *OutermostContext = CurContext;
605 while (!OutermostContext->isFileContext())
606 OutermostContext = OutermostContext->getLookupParent();
607
608 if (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
609 OutermostContext->Encloses(PrevDecl->getDeclContext())) {
610 SemanticContext = PrevDecl->getDeclContext();
611 } else {
612 // Declarations in outer scopes don't matter. However, the outermost
613 // context we computed is the semntic context for our new
614 // declaration.
615 PrevDecl = 0;
616 SemanticContext = OutermostContext;
617 }
618 } else if (PrevDecl && !isDeclInScope(PrevDecl, SemanticContext, S))
Douglas Gregorf187420f2009-06-17 23:37:01 +0000619 PrevDecl = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000620
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000621 // If there is a previous declaration with the same name, check
622 // whether this is a valid redeclaration.
Mike Stump11289f42009-09-09 15:08:12 +0000623 ClassTemplateDecl *PrevClassTemplate
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000624 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
Douglas Gregor7f34bae2009-10-09 21:11:42 +0000625
626 // We may have found the injected-class-name of a class template,
627 // class template partial specialization, or class template specialization.
628 // In these cases, grab the template that is being defined or specialized.
629 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
630 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
631 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
632 PrevClassTemplate
633 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
634 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
635 PrevClassTemplate
636 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
637 ->getSpecializedTemplate();
638 }
639 }
640
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000641 if (PrevClassTemplate) {
642 // Ensure that the template parameter lists are compatible.
643 if (!TemplateParameterListsAreEqual(TemplateParams,
644 PrevClassTemplate->getTemplateParameters(),
645 /*Complain=*/true))
Douglas Gregorc08f4892009-03-25 00:13:59 +0000646 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000647
648 // C++ [temp.class]p4:
649 // In a redeclaration, partial specialization, explicit
650 // specialization or explicit instantiation of a class template,
651 // the class-key shall agree in kind with the original class
652 // template declaration (7.1.5.3).
653 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Douglas Gregord9034f02009-05-14 16:41:31 +0000654 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind, KWLoc, *Name)) {
Mike Stump11289f42009-09-09 15:08:12 +0000655 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +0000656 << Name
Mike Stump11289f42009-09-09 15:08:12 +0000657 << CodeModificationHint::CreateReplacement(KWLoc,
Douglas Gregor170512f2009-04-01 23:51:29 +0000658 PrevRecordDecl->getKindName());
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000659 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregor170512f2009-04-01 23:51:29 +0000660 Kind = PrevRecordDecl->getTagKind();
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000661 }
662
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000663 // Check for redefinition of this class template.
John McCall9bb74a52009-07-31 02:45:11 +0000664 if (TUK == TUK_Definition) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000665 if (TagDecl *Def = PrevRecordDecl->getDefinition(Context)) {
666 Diag(NameLoc, diag::err_redefinition) << Name;
667 Diag(Def->getLocation(), diag::note_previous_definition);
668 // FIXME: Would it make sense to try to "forget" the previous
669 // definition, as part of error recovery?
Douglas Gregorc08f4892009-03-25 00:13:59 +0000670 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000671 }
672 }
673 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
674 // Maybe we will complain about the shadowed template parameter.
675 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
676 // Just pretend that we didn't see the previous declaration.
677 PrevDecl = 0;
678 } else if (PrevDecl) {
679 // C++ [temp]p5:
680 // A class template shall not have the same name as any other
681 // template, class, function, object, enumeration, enumerator,
682 // namespace, or type in the same scope (3.3), except as specified
683 // in (14.5.4).
684 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
685 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregorc08f4892009-03-25 00:13:59 +0000686 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000687 }
688
Douglas Gregordba32632009-02-10 19:49:53 +0000689 // Check the template parameter list of this declaration, possibly
690 // merging in the template parameter list from the previous class
691 // template declaration.
692 if (CheckTemplateParameterList(TemplateParams,
693 PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0))
694 Invalid = true;
Mike Stump11289f42009-09-09 15:08:12 +0000695
Douglas Gregore362cea2009-05-10 22:57:19 +0000696 // FIXME: If we had a scope specifier, we better have a previous template
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000697 // declaration!
698
Mike Stump11289f42009-09-09 15:08:12 +0000699 CXXRecordDecl *NewClass =
Douglas Gregor82fe3e32009-07-21 14:46:17 +0000700 CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name, KWLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000701 PrevClassTemplate?
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000702 PrevClassTemplate->getTemplatedDecl() : 0,
703 /*DelayTypeCreation=*/true);
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000704
705 ClassTemplateDecl *NewTemplate
706 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
707 DeclarationName(Name), TemplateParams,
Douglas Gregor90a1a652009-03-19 17:26:29 +0000708 NewClass, PrevClassTemplate);
Douglas Gregor97f1f1c2009-03-26 00:10:35 +0000709 NewClass->setDescribedClassTemplate(NewTemplate);
710
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000711 // Build the type for the class template declaration now.
Mike Stump11289f42009-09-09 15:08:12 +0000712 QualType T =
713 Context.getTypeDeclType(NewClass,
714 PrevClassTemplate?
715 PrevClassTemplate->getTemplatedDecl() : 0);
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000716 assert(T->isDependentType() && "Class template type is not dependent?");
717 (void)T;
718
Douglas Gregorcf915552009-10-13 16:30:37 +0000719 // If we are providing an explicit specialization of a member that is a
720 // class template, make a note of that.
721 if (PrevClassTemplate &&
722 PrevClassTemplate->getInstantiatedFromMemberTemplate())
723 PrevClassTemplate->setMemberSpecialization();
724
Anders Carlsson137108d2009-03-26 01:24:28 +0000725 // Set the access specifier.
Douglas Gregor3dad8422009-09-26 06:47:28 +0000726 if (!Invalid && TUK != TUK_Friend)
John McCall27b5c252009-09-14 21:59:20 +0000727 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
Mike Stump11289f42009-09-09 15:08:12 +0000728
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000729 // Set the lexical context of these templates
730 NewClass->setLexicalDeclContext(CurContext);
731 NewTemplate->setLexicalDeclContext(CurContext);
732
John McCall9bb74a52009-07-31 02:45:11 +0000733 if (TUK == TUK_Definition)
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000734 NewClass->startDefinition();
735
736 if (Attr)
Douglas Gregor758a8692009-06-17 21:51:59 +0000737 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000738
John McCall27b5c252009-09-14 21:59:20 +0000739 if (TUK != TUK_Friend)
740 PushOnScopeChains(NewTemplate, S);
741 else {
Douglas Gregor3dad8422009-09-26 06:47:28 +0000742 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
John McCall27b5c252009-09-14 21:59:20 +0000743 NewTemplate->setAccess(PrevClassTemplate->getAccess());
Douglas Gregor3dad8422009-09-26 06:47:28 +0000744 NewClass->setAccess(PrevClassTemplate->getAccess());
745 }
John McCall27b5c252009-09-14 21:59:20 +0000746
Douglas Gregor3dad8422009-09-26 06:47:28 +0000747 NewTemplate->setObjectOfFriendDecl(/* PreviouslyDeclared = */
748 PrevClassTemplate != NULL);
749
John McCall27b5c252009-09-14 21:59:20 +0000750 // Friend templates are visible in fairly strange ways.
751 if (!CurContext->isDependentContext()) {
752 DeclContext *DC = SemanticContext->getLookupContext();
753 DC->makeDeclVisibleInContext(NewTemplate, /* Recoverable = */ false);
754 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
755 PushOnScopeChains(NewTemplate, EnclosingScope,
756 /* AddToContext = */ false);
757 }
Douglas Gregor3dad8422009-09-26 06:47:28 +0000758
759 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
760 NewClass->getLocation(),
761 NewTemplate,
762 /*FIXME:*/NewClass->getLocation());
763 Friend->setAccess(AS_public);
764 CurContext->addDecl(Friend);
John McCall27b5c252009-09-14 21:59:20 +0000765 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000766
Douglas Gregordba32632009-02-10 19:49:53 +0000767 if (Invalid) {
768 NewTemplate->setInvalidDecl();
769 NewClass->setInvalidDecl();
770 }
Chris Lattner83f095c2009-03-28 19:18:32 +0000771 return DeclPtrTy::make(NewTemplate);
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000772}
773
Douglas Gregordba32632009-02-10 19:49:53 +0000774/// \brief Checks the validity of a template parameter list, possibly
775/// considering the template parameter list from a previous
776/// declaration.
777///
778/// If an "old" template parameter list is provided, it must be
779/// equivalent (per TemplateParameterListsAreEqual) to the "new"
780/// template parameter list.
781///
782/// \param NewParams Template parameter list for a new template
783/// declaration. This template parameter list will be updated with any
784/// default arguments that are carried through from the previous
785/// template parameter list.
786///
787/// \param OldParams If provided, template parameter list from a
788/// previous declaration of the same template. Default template
789/// arguments will be merged from the old template parameter list to
790/// the new template parameter list.
791///
792/// \returns true if an error occurred, false otherwise.
793bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
794 TemplateParameterList *OldParams) {
795 bool Invalid = false;
Mike Stump11289f42009-09-09 15:08:12 +0000796
Douglas Gregordba32632009-02-10 19:49:53 +0000797 // C++ [temp.param]p10:
798 // The set of default template-arguments available for use with a
799 // template declaration or definition is obtained by merging the
800 // default arguments from the definition (if in scope) and all
801 // declarations in scope in the same way default function
802 // arguments are (8.3.6).
803 bool SawDefaultArgument = false;
804 SourceLocation PreviousDefaultArgLoc;
Douglas Gregord32e0282009-02-09 23:23:08 +0000805
Anders Carlsson327865d2009-06-12 23:20:15 +0000806 bool SawParameterPack = false;
807 SourceLocation ParameterPackLoc;
808
Mike Stumpc89c8e32009-02-11 23:03:27 +0000809 // Dummy initialization to avoid warnings.
Douglas Gregor5bd22da2009-02-11 20:46:19 +0000810 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregordba32632009-02-10 19:49:53 +0000811 if (OldParams)
812 OldParam = OldParams->begin();
813
814 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
815 NewParamEnd = NewParams->end();
816 NewParam != NewParamEnd; ++NewParam) {
817 // Variables used to diagnose redundant default arguments
818 bool RedundantDefaultArg = false;
819 SourceLocation OldDefaultLoc;
820 SourceLocation NewDefaultLoc;
821
822 // Variables used to diagnose missing default arguments
823 bool MissingDefaultArg = false;
824
Anders Carlsson327865d2009-06-12 23:20:15 +0000825 // C++0x [temp.param]p11:
826 // If a template parameter of a class template is a template parameter pack,
827 // it must be the last template parameter.
828 if (SawParameterPack) {
Mike Stump11289f42009-09-09 15:08:12 +0000829 Diag(ParameterPackLoc,
Anders Carlsson327865d2009-06-12 23:20:15 +0000830 diag::err_template_param_pack_must_be_last_template_parameter);
831 Invalid = true;
832 }
833
Douglas Gregordba32632009-02-10 19:49:53 +0000834 // Merge default arguments for template type parameters.
835 if (TemplateTypeParmDecl *NewTypeParm
836 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
Mike Stump11289f42009-09-09 15:08:12 +0000837 TemplateTypeParmDecl *OldTypeParm
Douglas Gregordba32632009-02-10 19:49:53 +0000838 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +0000839
Anders Carlsson327865d2009-06-12 23:20:15 +0000840 if (NewTypeParm->isParameterPack()) {
841 assert(!NewTypeParm->hasDefaultArgument() &&
842 "Parameter packs can't have a default argument!");
843 SawParameterPack = true;
844 ParameterPackLoc = NewTypeParm->getLocation();
Mike Stump11289f42009-09-09 15:08:12 +0000845 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
Douglas Gregordba32632009-02-10 19:49:53 +0000846 NewTypeParm->hasDefaultArgument()) {
847 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
848 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
849 SawDefaultArgument = true;
850 RedundantDefaultArg = true;
851 PreviousDefaultArgLoc = NewDefaultLoc;
852 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
853 // Merge the default argument from the old declaration to the
854 // new declaration.
855 SawDefaultArgument = true;
856 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgument(),
857 OldTypeParm->getDefaultArgumentLoc(),
858 true);
859 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
860 } else if (NewTypeParm->hasDefaultArgument()) {
861 SawDefaultArgument = true;
862 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
863 } else if (SawDefaultArgument)
864 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +0000865 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
Douglas Gregordba32632009-02-10 19:49:53 +0000866 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000867 // Merge default arguments for non-type template parameters
Douglas Gregordba32632009-02-10 19:49:53 +0000868 NonTypeTemplateParmDecl *OldNonTypeParm
869 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +0000870 if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
Douglas Gregordba32632009-02-10 19:49:53 +0000871 NewNonTypeParm->hasDefaultArgument()) {
872 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
873 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
874 SawDefaultArgument = true;
875 RedundantDefaultArg = true;
876 PreviousDefaultArgLoc = NewDefaultLoc;
877 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
878 // Merge the default argument from the old declaration to the
879 // new declaration.
880 SawDefaultArgument = true;
881 // FIXME: We need to create a new kind of "default argument"
882 // expression that points to a previous template template
883 // parameter.
884 NewNonTypeParm->setDefaultArgument(
885 OldNonTypeParm->getDefaultArgument());
886 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
887 } else if (NewNonTypeParm->hasDefaultArgument()) {
888 SawDefaultArgument = true;
889 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
890 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +0000891 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +0000892 } else {
Douglas Gregordba32632009-02-10 19:49:53 +0000893 // Merge default arguments for template template parameters
Douglas Gregordba32632009-02-10 19:49:53 +0000894 TemplateTemplateParmDecl *NewTemplateParm
895 = cast<TemplateTemplateParmDecl>(*NewParam);
896 TemplateTemplateParmDecl *OldTemplateParm
897 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +0000898 if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
Douglas Gregordba32632009-02-10 19:49:53 +0000899 NewTemplateParm->hasDefaultArgument()) {
900 OldDefaultLoc = OldTemplateParm->getDefaultArgumentLoc();
901 NewDefaultLoc = NewTemplateParm->getDefaultArgumentLoc();
902 SawDefaultArgument = true;
903 RedundantDefaultArg = true;
904 PreviousDefaultArgLoc = NewDefaultLoc;
905 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
906 // Merge the default argument from the old declaration to the
907 // new declaration.
908 SawDefaultArgument = true;
Mike Stump87c57ac2009-05-16 07:39:55 +0000909 // FIXME: We need to create a new kind of "default argument" expression
910 // that points to a previous template template parameter.
Douglas Gregordba32632009-02-10 19:49:53 +0000911 NewTemplateParm->setDefaultArgument(
912 OldTemplateParm->getDefaultArgument());
913 PreviousDefaultArgLoc = OldTemplateParm->getDefaultArgumentLoc();
914 } else if (NewTemplateParm->hasDefaultArgument()) {
915 SawDefaultArgument = true;
916 PreviousDefaultArgLoc = NewTemplateParm->getDefaultArgumentLoc();
917 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +0000918 MissingDefaultArg = true;
Douglas Gregordba32632009-02-10 19:49:53 +0000919 }
920
921 if (RedundantDefaultArg) {
922 // C++ [temp.param]p12:
923 // A template-parameter shall not be given default arguments
924 // by two different declarations in the same scope.
925 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
926 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
927 Invalid = true;
928 } else if (MissingDefaultArg) {
929 // C++ [temp.param]p11:
930 // If a template-parameter has a default template-argument,
931 // all subsequent template-parameters shall have a default
932 // template-argument supplied.
Mike Stump11289f42009-09-09 15:08:12 +0000933 Diag((*NewParam)->getLocation(),
Douglas Gregordba32632009-02-10 19:49:53 +0000934 diag::err_template_param_default_arg_missing);
935 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
936 Invalid = true;
937 }
938
939 // If we have an old template parameter list that we're merging
940 // in, move on to the next parameter.
941 if (OldParams)
942 ++OldParam;
943 }
944
945 return Invalid;
946}
Douglas Gregord32e0282009-02-09 23:23:08 +0000947
Mike Stump11289f42009-09-09 15:08:12 +0000948/// \brief Match the given template parameter lists to the given scope
Douglas Gregord8d297c2009-07-21 23:53:31 +0000949/// specifier, returning the template parameter list that applies to the
950/// name.
951///
952/// \param DeclStartLoc the start of the declaration that has a scope
953/// specifier or a template parameter list.
Mike Stump11289f42009-09-09 15:08:12 +0000954///
Douglas Gregord8d297c2009-07-21 23:53:31 +0000955/// \param SS the scope specifier that will be matched to the given template
956/// parameter lists. This scope specifier precedes a qualified name that is
957/// being declared.
958///
959/// \param ParamLists the template parameter lists, from the outermost to the
960/// innermost template parameter lists.
961///
962/// \param NumParamLists the number of template parameter lists in ParamLists.
963///
Douglas Gregor5c0405d2009-10-07 22:35:40 +0000964/// \param IsExplicitSpecialization will be set true if the entity being
965/// declared is an explicit specialization, false otherwise.
966///
Mike Stump11289f42009-09-09 15:08:12 +0000967/// \returns the template parameter list, if any, that corresponds to the
Douglas Gregord8d297c2009-07-21 23:53:31 +0000968/// name that is preceded by the scope specifier @p SS. This template
969/// parameter list may be have template parameters (if we're declaring a
Mike Stump11289f42009-09-09 15:08:12 +0000970/// template) or may have no template parameters (if we're declaring a
Douglas Gregord8d297c2009-07-21 23:53:31 +0000971/// template specialization), or may be NULL (if we were's declaring isn't
972/// itself a template).
973TemplateParameterList *
974Sema::MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc,
975 const CXXScopeSpec &SS,
976 TemplateParameterList **ParamLists,
Douglas Gregor5c0405d2009-10-07 22:35:40 +0000977 unsigned NumParamLists,
978 bool &IsExplicitSpecialization) {
979 IsExplicitSpecialization = false;
980
Douglas Gregord8d297c2009-07-21 23:53:31 +0000981 // Find the template-ids that occur within the nested-name-specifier. These
982 // template-ids will match up with the template parameter lists.
983 llvm::SmallVector<const TemplateSpecializationType *, 4>
984 TemplateIdsInSpecifier;
985 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
986 NNS; NNS = NNS->getPrefix()) {
Mike Stump11289f42009-09-09 15:08:12 +0000987 if (const TemplateSpecializationType *SpecType
Douglas Gregord8d297c2009-07-21 23:53:31 +0000988 = dyn_cast_or_null<TemplateSpecializationType>(NNS->getAsType())) {
989 TemplateDecl *Template = SpecType->getTemplateName().getAsTemplateDecl();
990 if (!Template)
991 continue; // FIXME: should this be an error? probably...
Mike Stump11289f42009-09-09 15:08:12 +0000992
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000993 if (const RecordType *Record = SpecType->getAs<RecordType>()) {
Douglas Gregord8d297c2009-07-21 23:53:31 +0000994 ClassTemplateSpecializationDecl *SpecDecl
995 = cast<ClassTemplateSpecializationDecl>(Record->getDecl());
996 // If the nested name specifier refers to an explicit specialization,
997 // we don't need a template<> header.
Douglas Gregor82e22862009-09-16 00:01:48 +0000998 // FIXME: revisit this approach once we cope with specializations
Douglas Gregor15301382009-07-30 17:40:51 +0000999 // properly.
Douglas Gregord8d297c2009-07-21 23:53:31 +00001000 if (SpecDecl->getSpecializationKind() == TSK_ExplicitSpecialization)
1001 continue;
1002 }
Mike Stump11289f42009-09-09 15:08:12 +00001003
Douglas Gregord8d297c2009-07-21 23:53:31 +00001004 TemplateIdsInSpecifier.push_back(SpecType);
1005 }
1006 }
Mike Stump11289f42009-09-09 15:08:12 +00001007
Douglas Gregord8d297c2009-07-21 23:53:31 +00001008 // Reverse the list of template-ids in the scope specifier, so that we can
1009 // more easily match up the template-ids and the template parameter lists.
1010 std::reverse(TemplateIdsInSpecifier.begin(), TemplateIdsInSpecifier.end());
Mike Stump11289f42009-09-09 15:08:12 +00001011
Douglas Gregord8d297c2009-07-21 23:53:31 +00001012 SourceLocation FirstTemplateLoc = DeclStartLoc;
1013 if (NumParamLists)
1014 FirstTemplateLoc = ParamLists[0]->getTemplateLoc();
Mike Stump11289f42009-09-09 15:08:12 +00001015
Douglas Gregord8d297c2009-07-21 23:53:31 +00001016 // Match the template-ids found in the specifier to the template parameter
1017 // lists.
1018 unsigned Idx = 0;
1019 for (unsigned NumTemplateIds = TemplateIdsInSpecifier.size();
1020 Idx != NumTemplateIds; ++Idx) {
Douglas Gregor15301382009-07-30 17:40:51 +00001021 QualType TemplateId = QualType(TemplateIdsInSpecifier[Idx], 0);
1022 bool DependentTemplateId = TemplateId->isDependentType();
Douglas Gregord8d297c2009-07-21 23:53:31 +00001023 if (Idx >= NumParamLists) {
1024 // We have a template-id without a corresponding template parameter
1025 // list.
1026 if (DependentTemplateId) {
Mike Stump11289f42009-09-09 15:08:12 +00001027 // FIXME: the location information here isn't great.
1028 Diag(SS.getRange().getBegin(),
Douglas Gregord8d297c2009-07-21 23:53:31 +00001029 diag::err_template_spec_needs_template_parameters)
Douglas Gregor15301382009-07-30 17:40:51 +00001030 << TemplateId
Douglas Gregord8d297c2009-07-21 23:53:31 +00001031 << SS.getRange();
1032 } else {
1033 Diag(SS.getRange().getBegin(), diag::err_template_spec_needs_header)
1034 << SS.getRange()
1035 << CodeModificationHint::CreateInsertion(FirstTemplateLoc,
1036 "template<> ");
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001037 IsExplicitSpecialization = true;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001038 }
1039 return 0;
1040 }
Mike Stump11289f42009-09-09 15:08:12 +00001041
Douglas Gregord8d297c2009-07-21 23:53:31 +00001042 // Check the template parameter list against its corresponding template-id.
Douglas Gregor15301382009-07-30 17:40:51 +00001043 if (DependentTemplateId) {
Mike Stump11289f42009-09-09 15:08:12 +00001044 TemplateDecl *Template
Douglas Gregor15301382009-07-30 17:40:51 +00001045 = TemplateIdsInSpecifier[Idx]->getTemplateName().getAsTemplateDecl();
1046
Mike Stump11289f42009-09-09 15:08:12 +00001047 if (ClassTemplateDecl *ClassTemplate
Douglas Gregor15301382009-07-30 17:40:51 +00001048 = dyn_cast<ClassTemplateDecl>(Template)) {
1049 TemplateParameterList *ExpectedTemplateParams = 0;
1050 // Is this template-id naming the primary template?
1051 if (Context.hasSameType(TemplateId,
1052 ClassTemplate->getInjectedClassNameType(Context)))
1053 ExpectedTemplateParams = ClassTemplate->getTemplateParameters();
1054 // ... or a partial specialization?
1055 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
1056 = ClassTemplate->findPartialSpecialization(TemplateId))
1057 ExpectedTemplateParams = PartialSpec->getTemplateParameters();
1058
1059 if (ExpectedTemplateParams)
Mike Stump11289f42009-09-09 15:08:12 +00001060 TemplateParameterListsAreEqual(ParamLists[Idx],
Douglas Gregor15301382009-07-30 17:40:51 +00001061 ExpectedTemplateParams,
1062 true);
Mike Stump11289f42009-09-09 15:08:12 +00001063 }
Douglas Gregor15301382009-07-30 17:40:51 +00001064 } else if (ParamLists[Idx]->size() > 0)
Mike Stump11289f42009-09-09 15:08:12 +00001065 Diag(ParamLists[Idx]->getTemplateLoc(),
Douglas Gregor15301382009-07-30 17:40:51 +00001066 diag::err_template_param_list_matches_nontemplate)
1067 << TemplateId
1068 << ParamLists[Idx]->getSourceRange();
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001069 else
1070 IsExplicitSpecialization = true;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001071 }
Mike Stump11289f42009-09-09 15:08:12 +00001072
Douglas Gregord8d297c2009-07-21 23:53:31 +00001073 // If there were at least as many template-ids as there were template
1074 // parameter lists, then there are no template parameter lists remaining for
1075 // the declaration itself.
1076 if (Idx >= NumParamLists)
1077 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001078
Douglas Gregord8d297c2009-07-21 23:53:31 +00001079 // If there were too many template parameter lists, complain about that now.
1080 if (Idx != NumParamLists - 1) {
1081 while (Idx < NumParamLists - 1) {
Mike Stump11289f42009-09-09 15:08:12 +00001082 Diag(ParamLists[Idx]->getTemplateLoc(),
Douglas Gregord8d297c2009-07-21 23:53:31 +00001083 diag::err_template_spec_extra_headers)
1084 << SourceRange(ParamLists[Idx]->getTemplateLoc(),
1085 ParamLists[Idx]->getRAngleLoc());
1086 ++Idx;
1087 }
1088 }
Mike Stump11289f42009-09-09 15:08:12 +00001089
Douglas Gregord8d297c2009-07-21 23:53:31 +00001090 // Return the last template parameter list, which corresponds to the
1091 // entity being declared.
1092 return ParamLists[NumParamLists - 1];
1093}
1094
Douglas Gregorc40290e2009-03-09 23:48:35 +00001095/// \brief Translates template arguments as provided by the parser
1096/// into template arguments used by semantic analysis.
Douglas Gregor0e876e02009-09-25 23:53:26 +00001097void Sema::translateTemplateArguments(ASTTemplateArgsPtr &TemplateArgsIn,
1098 SourceLocation *TemplateArgLocs,
Douglas Gregorc40290e2009-03-09 23:48:35 +00001099 llvm::SmallVector<TemplateArgument, 16> &TemplateArgs) {
1100 TemplateArgs.reserve(TemplateArgsIn.size());
1101
1102 void **Args = TemplateArgsIn.getArgs();
1103 bool *ArgIsType = TemplateArgsIn.getArgIsType();
1104 for (unsigned Arg = 0, Last = TemplateArgsIn.size(); Arg != Last; ++Arg) {
1105 TemplateArgs.push_back(
1106 ArgIsType[Arg]? TemplateArgument(TemplateArgLocs[Arg],
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00001107 //FIXME: Preserve type source info.
1108 Sema::GetTypeFromParser(Args[Arg]))
Douglas Gregorc40290e2009-03-09 23:48:35 +00001109 : TemplateArgument(reinterpret_cast<Expr *>(Args[Arg])));
1110 }
1111}
1112
Douglas Gregordc572a32009-03-30 22:58:21 +00001113QualType Sema::CheckTemplateIdType(TemplateName Name,
1114 SourceLocation TemplateLoc,
1115 SourceLocation LAngleLoc,
1116 const TemplateArgument *TemplateArgs,
1117 unsigned NumTemplateArgs,
1118 SourceLocation RAngleLoc) {
1119 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregorb67535d2009-03-31 00:43:58 +00001120 if (!Template) {
1121 // The template name does not resolve to a template, so we just
1122 // build a dependent template-id type.
Douglas Gregorb67535d2009-03-31 00:43:58 +00001123 return Context.getTemplateSpecializationType(Name, TemplateArgs,
Douglas Gregora8e02e72009-07-28 23:00:59 +00001124 NumTemplateArgs);
Douglas Gregorb67535d2009-03-31 00:43:58 +00001125 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001126
Douglas Gregorc40290e2009-03-09 23:48:35 +00001127 // Check that the template argument list is well-formed for this
1128 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001129 TemplateArgumentListBuilder Converted(Template->getTemplateParameters(),
1130 NumTemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00001131 if (CheckTemplateArgumentList(Template, TemplateLoc, LAngleLoc,
Douglas Gregorc40290e2009-03-09 23:48:35 +00001132 TemplateArgs, NumTemplateArgs, RAngleLoc,
Douglas Gregore3f1f352009-07-01 00:28:38 +00001133 false, Converted))
Douglas Gregorc40290e2009-03-09 23:48:35 +00001134 return QualType();
1135
Mike Stump11289f42009-09-09 15:08:12 +00001136 assert((Converted.structuredSize() ==
Douglas Gregordc572a32009-03-30 22:58:21 +00001137 Template->getTemplateParameters()->size()) &&
Douglas Gregorc40290e2009-03-09 23:48:35 +00001138 "Converted template argument list is too short!");
1139
1140 QualType CanonType;
1141
Douglas Gregordc572a32009-03-30 22:58:21 +00001142 if (TemplateSpecializationType::anyDependentTemplateArguments(
Douglas Gregorc40290e2009-03-09 23:48:35 +00001143 TemplateArgs,
1144 NumTemplateArgs)) {
1145 // This class template specialization is a dependent
1146 // type. Therefore, its canonical type is another class template
1147 // specialization type that contains all of the converted
1148 // arguments in canonical form. This ensures that, e.g., A<T> and
1149 // A<T, T> have identical types when A is declared as:
1150 //
1151 // template<typename T, typename U = T> struct A;
Douglas Gregor6bc50582009-05-07 06:41:52 +00001152 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
Mike Stump11289f42009-09-09 15:08:12 +00001153 CanonType = Context.getTemplateSpecializationType(CanonName,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001154 Converted.getFlatArguments(),
1155 Converted.flatSize());
Mike Stump11289f42009-09-09 15:08:12 +00001156
Douglas Gregora8e02e72009-07-28 23:00:59 +00001157 // FIXME: CanonType is not actually the canonical type, and unfortunately
1158 // it is a TemplateTypeSpecializationType that we will never use again.
1159 // In the future, we need to teach getTemplateSpecializationType to only
1160 // build the canonical type and return that to us.
1161 CanonType = Context.getCanonicalType(CanonType);
Mike Stump11289f42009-09-09 15:08:12 +00001162 } else if (ClassTemplateDecl *ClassTemplate
Douglas Gregordc572a32009-03-30 22:58:21 +00001163 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00001164 // Find the class template specialization declaration that
1165 // corresponds to these arguments.
1166 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00001167 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001168 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00001169 Converted.flatSize(),
1170 Context);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001171 void *InsertPos = 0;
1172 ClassTemplateSpecializationDecl *Decl
1173 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
1174 if (!Decl) {
1175 // This is the first time we have referenced this class template
1176 // specialization. Create the canonical declaration and add it to
1177 // the set of specializations.
Mike Stump11289f42009-09-09 15:08:12 +00001178 Decl = ClassTemplateSpecializationDecl::Create(Context,
Anders Carlsson8aa89d42009-06-05 03:43:12 +00001179 ClassTemplate->getDeclContext(),
John McCall1806c272009-09-11 07:25:08 +00001180 ClassTemplate->getLocation(),
Anders Carlsson8aa89d42009-06-05 03:43:12 +00001181 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001182 Converted, 0);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001183 ClassTemplate->getSpecializations().InsertNode(Decl, InsertPos);
1184 Decl->setLexicalDeclContext(CurContext);
1185 }
1186
1187 CanonType = Context.getTypeDeclType(Decl);
1188 }
Mike Stump11289f42009-09-09 15:08:12 +00001189
Douglas Gregorc40290e2009-03-09 23:48:35 +00001190 // Build the fully-sugared type for this class template
1191 // specialization, which refers back to the class template
1192 // specialization we created or found.
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00001193 //FIXME: Preserve type source info.
Douglas Gregordc572a32009-03-30 22:58:21 +00001194 return Context.getTemplateSpecializationType(Name, TemplateArgs,
1195 NumTemplateArgs, CanonType);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001196}
1197
Douglas Gregor67a65642009-02-17 23:15:12 +00001198Action::TypeResult
Douglas Gregordc572a32009-03-30 22:58:21 +00001199Sema::ActOnTemplateIdType(TemplateTy TemplateD, SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00001200 SourceLocation LAngleLoc,
Douglas Gregordc572a32009-03-30 22:58:21 +00001201 ASTTemplateArgsPtr TemplateArgsIn,
1202 SourceLocation *TemplateArgLocs,
John McCalld8fe9af2009-09-08 17:47:29 +00001203 SourceLocation RAngleLoc) {
Douglas Gregordc572a32009-03-30 22:58:21 +00001204 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Douglas Gregor8bf42052009-02-09 18:46:07 +00001205
Douglas Gregorc40290e2009-03-09 23:48:35 +00001206 // Translate the parser's template argument list in our AST format.
1207 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
1208 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
Douglas Gregord32e0282009-02-09 23:23:08 +00001209
Douglas Gregordc572a32009-03-30 22:58:21 +00001210 QualType Result = CheckTemplateIdType(Template, TemplateLoc, LAngleLoc,
Jay Foad7d0479f2009-05-21 09:52:38 +00001211 TemplateArgs.data(),
1212 TemplateArgs.size(),
Douglas Gregordc572a32009-03-30 22:58:21 +00001213 RAngleLoc);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001214 TemplateArgsIn.release();
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00001215
1216 if (Result.isNull())
1217 return true;
1218
John McCalld8fe9af2009-09-08 17:47:29 +00001219 return Result.getAsOpaquePtr();
1220}
John McCall06f6fe8d2009-09-04 01:14:41 +00001221
John McCalld8fe9af2009-09-08 17:47:29 +00001222Sema::TypeResult Sema::ActOnTagTemplateIdType(TypeResult TypeResult,
1223 TagUseKind TUK,
1224 DeclSpec::TST TagSpec,
1225 SourceLocation TagLoc) {
1226 if (TypeResult.isInvalid())
1227 return Sema::TypeResult();
John McCall06f6fe8d2009-09-04 01:14:41 +00001228
John McCalld8fe9af2009-09-08 17:47:29 +00001229 QualType Type = QualType::getFromOpaquePtr(TypeResult.get());
John McCall06f6fe8d2009-09-04 01:14:41 +00001230
John McCalld8fe9af2009-09-08 17:47:29 +00001231 // Verify the tag specifier.
1232 TagDecl::TagKind TagKind = TagDecl::getTagKindForTypeSpec(TagSpec);
Mike Stump11289f42009-09-09 15:08:12 +00001233
John McCalld8fe9af2009-09-08 17:47:29 +00001234 if (const RecordType *RT = Type->getAs<RecordType>()) {
1235 RecordDecl *D = RT->getDecl();
1236
1237 IdentifierInfo *Id = D->getIdentifier();
1238 assert(Id && "templated class must have an identifier");
1239
1240 if (!isAcceptableTagRedeclaration(D, TagKind, TagLoc, *Id)) {
1241 Diag(TagLoc, diag::err_use_with_wrong_tag)
John McCall7f41d982009-09-11 04:59:25 +00001242 << Type
John McCalld8fe9af2009-09-08 17:47:29 +00001243 << CodeModificationHint::CreateReplacement(SourceRange(TagLoc),
1244 D->getKindName());
John McCall7f41d982009-09-11 04:59:25 +00001245 Diag(D->getLocation(), diag::note_previous_use);
John McCall06f6fe8d2009-09-04 01:14:41 +00001246 }
1247 }
1248
John McCalld8fe9af2009-09-08 17:47:29 +00001249 QualType ElabType = Context.getElaboratedType(Type, TagKind);
1250
1251 return ElabType.getAsOpaquePtr();
Douglas Gregor8bf42052009-02-09 18:46:07 +00001252}
1253
Douglas Gregord019ff62009-10-22 17:20:55 +00001254Sema::OwningExprResult Sema::BuildTemplateIdExpr(NestedNameSpecifier *Qualifier,
1255 SourceRange QualifierRange,
1256 TemplateName Template,
Douglas Gregora727cb92009-06-30 22:34:41 +00001257 SourceLocation TemplateNameLoc,
1258 SourceLocation LAngleLoc,
1259 const TemplateArgument *TemplateArgs,
1260 unsigned NumTemplateArgs,
1261 SourceLocation RAngleLoc) {
1262 // FIXME: Can we do any checking at this point? I guess we could check the
1263 // template arguments that we have against the template name, if the template
Mike Stump11289f42009-09-09 15:08:12 +00001264 // name refers to a single template. That's not a terribly common case,
Douglas Gregora727cb92009-06-30 22:34:41 +00001265 // though.
Douglas Gregor3c8a0cf2009-10-22 07:19:14 +00001266
1267 // Cope with an implicit member access in a C++ non-static member function.
1268 NamedDecl *D = Template.getAsTemplateDecl();
1269 if (!D)
1270 D = Template.getAsOverloadedFunctionDecl();
1271
Douglas Gregord019ff62009-10-22 17:20:55 +00001272 CXXScopeSpec SS;
1273 SS.setRange(QualifierRange);
1274 SS.setScopeRep(Qualifier);
Douglas Gregor3c8a0cf2009-10-22 07:19:14 +00001275 QualType ThisType, MemberType;
Douglas Gregord019ff62009-10-22 17:20:55 +00001276 if (D && isImplicitMemberReference(&SS, D, TemplateNameLoc,
Douglas Gregor3c8a0cf2009-10-22 07:19:14 +00001277 ThisType, MemberType)) {
1278 Expr *This = new (Context) CXXThisExpr(SourceLocation(), ThisType);
1279 return Owned(MemberExpr::Create(Context, This, true,
Douglas Gregord019ff62009-10-22 17:20:55 +00001280 Qualifier, QualifierRange,
Douglas Gregor3c8a0cf2009-10-22 07:19:14 +00001281 D, TemplateNameLoc, true,
1282 LAngleLoc, TemplateArgs,
1283 NumTemplateArgs, RAngleLoc,
1284 Context.OverloadTy));
1285 }
1286
Douglas Gregord019ff62009-10-22 17:20:55 +00001287 return Owned(TemplateIdRefExpr::Create(Context, Context.OverloadTy,
1288 Qualifier, QualifierRange,
Douglas Gregora727cb92009-06-30 22:34:41 +00001289 Template, TemplateNameLoc, LAngleLoc,
Mike Stump11289f42009-09-09 15:08:12 +00001290 TemplateArgs,
Douglas Gregora727cb92009-06-30 22:34:41 +00001291 NumTemplateArgs, RAngleLoc));
1292}
1293
Douglas Gregord019ff62009-10-22 17:20:55 +00001294Sema::OwningExprResult Sema::ActOnTemplateIdExpr(const CXXScopeSpec &SS,
1295 TemplateTy TemplateD,
Douglas Gregora727cb92009-06-30 22:34:41 +00001296 SourceLocation TemplateNameLoc,
1297 SourceLocation LAngleLoc,
1298 ASTTemplateArgsPtr TemplateArgsIn,
1299 SourceLocation *TemplateArgLocs,
1300 SourceLocation RAngleLoc) {
1301 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Mike Stump11289f42009-09-09 15:08:12 +00001302
Douglas Gregora727cb92009-06-30 22:34:41 +00001303 // Translate the parser's template argument list in our AST format.
1304 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
1305 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
Douglas Gregorb77af8f2009-07-22 20:55:49 +00001306 TemplateArgsIn.release();
Mike Stump11289f42009-09-09 15:08:12 +00001307
Douglas Gregord019ff62009-10-22 17:20:55 +00001308 return BuildTemplateIdExpr((NestedNameSpecifier *)SS.getScopeRep(),
1309 SS.getRange(),
1310 Template, TemplateNameLoc, LAngleLoc,
Douglas Gregora727cb92009-06-30 22:34:41 +00001311 TemplateArgs.data(), TemplateArgs.size(),
1312 RAngleLoc);
1313}
1314
Douglas Gregor84f14dd2009-09-01 00:37:14 +00001315Sema::OwningExprResult
1316Sema::ActOnMemberTemplateIdReferenceExpr(Scope *S, ExprArg Base,
1317 SourceLocation OpLoc,
1318 tok::TokenKind OpKind,
1319 const CXXScopeSpec &SS,
1320 TemplateTy TemplateD,
1321 SourceLocation TemplateNameLoc,
1322 SourceLocation LAngleLoc,
1323 ASTTemplateArgsPtr TemplateArgsIn,
1324 SourceLocation *TemplateArgLocs,
1325 SourceLocation RAngleLoc) {
1326 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Mike Stump11289f42009-09-09 15:08:12 +00001327
Douglas Gregor84f14dd2009-09-01 00:37:14 +00001328 // FIXME: We're going to end up looking up the template based on its name,
1329 // twice!
1330 DeclarationName Name;
1331 if (TemplateDecl *ActualTemplate = Template.getAsTemplateDecl())
1332 Name = ActualTemplate->getDeclName();
1333 else if (OverloadedFunctionDecl *Ovl = Template.getAsOverloadedFunctionDecl())
1334 Name = Ovl->getDeclName();
1335 else
Douglas Gregor308047d2009-09-09 00:23:06 +00001336 Name = Template.getAsDependentTemplateName()->getName();
Mike Stump11289f42009-09-09 15:08:12 +00001337
Douglas Gregor84f14dd2009-09-01 00:37:14 +00001338 // Translate the parser's template argument list in our AST format.
1339 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
1340 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
1341 TemplateArgsIn.release();
Mike Stump11289f42009-09-09 15:08:12 +00001342
Douglas Gregor84f14dd2009-09-01 00:37:14 +00001343 // Do we have the save the actual template name? We might need it...
1344 return BuildMemberReferenceExpr(S, move(Base), OpLoc, OpKind, TemplateNameLoc,
1345 Name, true, LAngleLoc,
1346 TemplateArgs.data(), TemplateArgs.size(),
Mike Stump11289f42009-09-09 15:08:12 +00001347 RAngleLoc, DeclPtrTy(), &SS);
Douglas Gregor84f14dd2009-09-01 00:37:14 +00001348}
1349
Douglas Gregorb67535d2009-03-31 00:43:58 +00001350/// \brief Form a dependent template name.
1351///
1352/// This action forms a dependent template name given the template
1353/// name and its (presumably dependent) scope specifier. For
1354/// example, given "MetaFun::template apply", the scope specifier \p
1355/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
1356/// of the "template" keyword, and "apply" is the \p Name.
Mike Stump11289f42009-09-09 15:08:12 +00001357Sema::TemplateTy
Douglas Gregorb67535d2009-03-31 00:43:58 +00001358Sema::ActOnDependentTemplateName(SourceLocation TemplateKWLoc,
1359 const IdentifierInfo &Name,
1360 SourceLocation NameLoc,
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001361 const CXXScopeSpec &SS,
1362 TypeTy *ObjectType) {
Mike Stump11289f42009-09-09 15:08:12 +00001363 if ((ObjectType &&
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001364 computeDeclContext(QualType::getFromOpaquePtr(ObjectType))) ||
1365 (SS.isSet() && computeDeclContext(SS, false))) {
Douglas Gregorb67535d2009-03-31 00:43:58 +00001366 // C++0x [temp.names]p5:
1367 // If a name prefixed by the keyword template is not the name of
1368 // a template, the program is ill-formed. [Note: the keyword
1369 // template may not be applied to non-template members of class
1370 // templates. -end note ] [ Note: as is the case with the
1371 // typename prefix, the template prefix is allowed in cases
1372 // where it is not strictly necessary; i.e., when the
1373 // nested-name-specifier or the expression on the left of the ->
1374 // or . is not dependent on a template-parameter, or the use
1375 // does not appear in the scope of a template. -end note]
1376 //
1377 // Note: C++03 was more strict here, because it banned the use of
1378 // the "template" keyword prior to a template-name that was not a
1379 // dependent name. C++ DR468 relaxed this requirement (the
1380 // "template" keyword is now permitted). We follow the C++0x
1381 // rules, even in C++03 mode, retroactively applying the DR.
1382 TemplateTy Template;
Mike Stump11289f42009-09-09 15:08:12 +00001383 TemplateNameKind TNK = isTemplateName(0, Name, NameLoc, &SS, ObjectType,
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001384 false, Template);
Douglas Gregorb67535d2009-03-31 00:43:58 +00001385 if (TNK == TNK_Non_template) {
1386 Diag(NameLoc, diag::err_template_kw_refers_to_non_template)
1387 << &Name;
1388 return TemplateTy();
1389 }
1390
1391 return Template;
1392 }
1393
Mike Stump11289f42009-09-09 15:08:12 +00001394 NestedNameSpecifier *Qualifier
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001395 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Douglas Gregorb67535d2009-03-31 00:43:58 +00001396 return TemplateTy::make(Context.getDependentTemplateName(Qualifier, &Name));
1397}
1398
Mike Stump11289f42009-09-09 15:08:12 +00001399bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001400 const TemplateArgument &Arg,
1401 TemplateArgumentListBuilder &Converted) {
1402 // Check template type parameter.
1403 if (Arg.getKind() != TemplateArgument::Type) {
1404 // C++ [temp.arg.type]p1:
1405 // A template-argument for a template-parameter which is a
1406 // type shall be a type-id.
1407
1408 // We have a template type parameter but the template argument
1409 // is not a type.
1410 Diag(Arg.getLocation(), diag::err_template_arg_must_be_type);
1411 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00001412
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001413 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001414 }
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001415
1416 if (CheckTemplateArgument(Param, Arg.getAsType(), Arg.getLocation()))
1417 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001418
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001419 // Add the converted template type argument.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001420 Converted.Append(
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001421 TemplateArgument(Arg.getLocation(),
1422 Context.getCanonicalType(Arg.getAsType())));
1423 return false;
1424}
1425
Douglas Gregord32e0282009-02-09 23:23:08 +00001426/// \brief Check that the given template argument list is well-formed
1427/// for specializing the given template.
1428bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
1429 SourceLocation TemplateLoc,
1430 SourceLocation LAngleLoc,
Douglas Gregorc40290e2009-03-09 23:48:35 +00001431 const TemplateArgument *TemplateArgs,
1432 unsigned NumTemplateArgs,
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001433 SourceLocation RAngleLoc,
Douglas Gregore3f1f352009-07-01 00:28:38 +00001434 bool PartialTemplateArgs,
Anders Carlsson8aa89d42009-06-05 03:43:12 +00001435 TemplateArgumentListBuilder &Converted) {
Douglas Gregord32e0282009-02-09 23:23:08 +00001436 TemplateParameterList *Params = Template->getTemplateParameters();
1437 unsigned NumParams = Params->size();
Douglas Gregorc40290e2009-03-09 23:48:35 +00001438 unsigned NumArgs = NumTemplateArgs;
Douglas Gregord32e0282009-02-09 23:23:08 +00001439 bool Invalid = false;
1440
Mike Stump11289f42009-09-09 15:08:12 +00001441 bool HasParameterPack =
Anders Carlsson15201f12009-06-13 02:08:00 +00001442 NumParams > 0 && Params->getParam(NumParams - 1)->isTemplateParameterPack();
Mike Stump11289f42009-09-09 15:08:12 +00001443
Anders Carlsson15201f12009-06-13 02:08:00 +00001444 if ((NumArgs > NumParams && !HasParameterPack) ||
Douglas Gregore3f1f352009-07-01 00:28:38 +00001445 (NumArgs < Params->getMinRequiredArguments() &&
1446 !PartialTemplateArgs)) {
Douglas Gregord32e0282009-02-09 23:23:08 +00001447 // FIXME: point at either the first arg beyond what we can handle,
1448 // or the '>', depending on whether we have too many or too few
1449 // arguments.
1450 SourceRange Range;
1451 if (NumArgs > NumParams)
Douglas Gregorc40290e2009-03-09 23:48:35 +00001452 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
Douglas Gregord32e0282009-02-09 23:23:08 +00001453 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
1454 << (NumArgs > NumParams)
1455 << (isa<ClassTemplateDecl>(Template)? 0 :
1456 isa<FunctionTemplateDecl>(Template)? 1 :
1457 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
1458 << Template << Range;
Douglas Gregorf8f86832009-02-11 18:16:40 +00001459 Diag(Template->getLocation(), diag::note_template_decl_here)
1460 << Params->getSourceRange();
Douglas Gregord32e0282009-02-09 23:23:08 +00001461 Invalid = true;
1462 }
Mike Stump11289f42009-09-09 15:08:12 +00001463
1464 // C++ [temp.arg]p1:
Douglas Gregord32e0282009-02-09 23:23:08 +00001465 // [...] The type and form of each template-argument specified in
1466 // a template-id shall match the type and form specified for the
1467 // corresponding parameter declared by the template in its
1468 // template-parameter-list.
1469 unsigned ArgIdx = 0;
1470 for (TemplateParameterList::iterator Param = Params->begin(),
1471 ParamEnd = Params->end();
1472 Param != ParamEnd; ++Param, ++ArgIdx) {
Douglas Gregore3f1f352009-07-01 00:28:38 +00001473 if (ArgIdx > NumArgs && PartialTemplateArgs)
1474 break;
Mike Stump11289f42009-09-09 15:08:12 +00001475
Douglas Gregord32e0282009-02-09 23:23:08 +00001476 // Decode the template argument
Douglas Gregorc40290e2009-03-09 23:48:35 +00001477 TemplateArgument Arg;
Douglas Gregord32e0282009-02-09 23:23:08 +00001478 if (ArgIdx >= NumArgs) {
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001479 // Retrieve the default template argument from the template
1480 // parameter.
1481 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
Anders Carlsson15201f12009-06-13 02:08:00 +00001482 if (TTP->isParameterPack()) {
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001483 // We have an empty argument pack.
1484 Converted.BeginPack();
1485 Converted.EndPack();
Anders Carlsson15201f12009-06-13 02:08:00 +00001486 break;
1487 }
Mike Stump11289f42009-09-09 15:08:12 +00001488
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001489 if (!TTP->hasDefaultArgument())
1490 break;
1491
Douglas Gregorc40290e2009-03-09 23:48:35 +00001492 QualType ArgType = TTP->getDefaultArgument();
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001493
1494 // If the argument type is dependent, instantiate it now based
1495 // on the previously-computed template arguments.
Douglas Gregor79cf6032009-03-10 20:44:00 +00001496 if (ArgType->isDependentType()) {
Mike Stump11289f42009-09-09 15:08:12 +00001497 InstantiatingTemplate Inst(*this, TemplateLoc,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001498 Template, Converted.getFlatArguments(),
Anders Carlsson8aa89d42009-06-05 03:43:12 +00001499 Converted.flatSize(),
Douglas Gregor79cf6032009-03-10 20:44:00 +00001500 SourceRange(TemplateLoc, RAngleLoc));
Douglas Gregord002c7b2009-05-11 23:53:27 +00001501
Anders Carlssonc8e71132009-06-05 04:47:51 +00001502 TemplateArgumentList TemplateArgs(Context, Converted,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001503 /*TakeArgs=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00001504 ArgType = SubstType(ArgType,
Douglas Gregor01afeef2009-08-28 20:31:08 +00001505 MultiLevelTemplateArgumentList(TemplateArgs),
John McCall76d824f2009-08-25 22:02:44 +00001506 TTP->getDefaultArgumentLoc(),
1507 TTP->getDeclName());
Douglas Gregor79cf6032009-03-10 20:44:00 +00001508 }
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001509
1510 if (ArgType.isNull())
Douglas Gregor17c0d7b2009-02-28 00:25:32 +00001511 return true;
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001512
Douglas Gregorc40290e2009-03-09 23:48:35 +00001513 Arg = TemplateArgument(TTP->getLocation(), ArgType);
Mike Stump11289f42009-09-09 15:08:12 +00001514 } else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001515 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
1516 if (!NTTP->hasDefaultArgument())
1517 break;
1518
Mike Stump11289f42009-09-09 15:08:12 +00001519 InstantiatingTemplate Inst(*this, TemplateLoc,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001520 Template, Converted.getFlatArguments(),
Anders Carlsson40ed3442009-06-11 16:06:49 +00001521 Converted.flatSize(),
1522 SourceRange(TemplateLoc, RAngleLoc));
Mike Stump11289f42009-09-09 15:08:12 +00001523
Anders Carlsson40ed3442009-06-11 16:06:49 +00001524 TemplateArgumentList TemplateArgs(Context, Converted,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001525 /*TakeArgs=*/false);
Anders Carlsson40ed3442009-06-11 16:06:49 +00001526
Mike Stump11289f42009-09-09 15:08:12 +00001527 Sema::OwningExprResult E
1528 = SubstExpr(NTTP->getDefaultArgument(),
Douglas Gregor01afeef2009-08-28 20:31:08 +00001529 MultiLevelTemplateArgumentList(TemplateArgs));
Anders Carlsson40ed3442009-06-11 16:06:49 +00001530 if (E.isInvalid())
1531 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001532
Anders Carlsson40ed3442009-06-11 16:06:49 +00001533 Arg = TemplateArgument(E.takeAs<Expr>());
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001534 } else {
Mike Stump11289f42009-09-09 15:08:12 +00001535 TemplateTemplateParmDecl *TempParm
1536 = cast<TemplateTemplateParmDecl>(*Param);
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001537
1538 if (!TempParm->hasDefaultArgument())
1539 break;
1540
John McCall76d824f2009-08-25 22:02:44 +00001541 // FIXME: Subst default argument
Douglas Gregorc40290e2009-03-09 23:48:35 +00001542 Arg = TemplateArgument(TempParm->getDefaultArgument());
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001543 }
1544 } else {
1545 // Retrieve the template argument produced by the user.
Douglas Gregorc40290e2009-03-09 23:48:35 +00001546 Arg = TemplateArgs[ArgIdx];
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001547 }
1548
Douglas Gregord32e0282009-02-09 23:23:08 +00001549
1550 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
Anders Carlsson15201f12009-06-13 02:08:00 +00001551 if (TTP->isParameterPack()) {
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001552 Converted.BeginPack();
Anders Carlsson15201f12009-06-13 02:08:00 +00001553 // Check all the remaining arguments (if any).
1554 for (; ArgIdx < NumArgs; ++ArgIdx) {
1555 if (CheckTemplateTypeArgument(TTP, TemplateArgs[ArgIdx], Converted))
1556 Invalid = true;
1557 }
Mike Stump11289f42009-09-09 15:08:12 +00001558
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001559 Converted.EndPack();
Anders Carlsson15201f12009-06-13 02:08:00 +00001560 } else {
1561 if (CheckTemplateTypeArgument(TTP, Arg, Converted))
1562 Invalid = true;
1563 }
Mike Stump11289f42009-09-09 15:08:12 +00001564 } else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregord32e0282009-02-09 23:23:08 +00001565 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
1566 // Check non-type template parameters.
Douglas Gregor463421d2009-03-03 04:44:36 +00001567
John McCall76d824f2009-08-25 22:02:44 +00001568 // Do substitution on the type of the non-type template parameter
1569 // with the template arguments we've seen thus far.
Douglas Gregor463421d2009-03-03 04:44:36 +00001570 QualType NTTPType = NTTP->getType();
1571 if (NTTPType->isDependentType()) {
John McCall76d824f2009-08-25 22:02:44 +00001572 // Do substitution on the type of the non-type template parameter.
Mike Stump11289f42009-09-09 15:08:12 +00001573 InstantiatingTemplate Inst(*this, TemplateLoc,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001574 Template, Converted.getFlatArguments(),
Anders Carlsson8aa89d42009-06-05 03:43:12 +00001575 Converted.flatSize(),
Douglas Gregor79cf6032009-03-10 20:44:00 +00001576 SourceRange(TemplateLoc, RAngleLoc));
1577
Anders Carlssonc8e71132009-06-05 04:47:51 +00001578 TemplateArgumentList TemplateArgs(Context, Converted,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001579 /*TakeArgs=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00001580 NTTPType = SubstType(NTTPType,
Douglas Gregor39cacdb2009-08-28 20:50:45 +00001581 MultiLevelTemplateArgumentList(TemplateArgs),
John McCall76d824f2009-08-25 22:02:44 +00001582 NTTP->getLocation(),
1583 NTTP->getDeclName());
Douglas Gregor463421d2009-03-03 04:44:36 +00001584 // If that worked, check the non-type template parameter type
1585 // for validity.
1586 if (!NTTPType.isNull())
Mike Stump11289f42009-09-09 15:08:12 +00001587 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
Douglas Gregor463421d2009-03-03 04:44:36 +00001588 NTTP->getLocation());
Douglas Gregor463421d2009-03-03 04:44:36 +00001589 if (NTTPType.isNull()) {
1590 Invalid = true;
1591 break;
1592 }
1593 }
1594
Douglas Gregorc40290e2009-03-09 23:48:35 +00001595 switch (Arg.getKind()) {
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001596 case TemplateArgument::Null:
1597 assert(false && "Should never see a NULL template argument here");
1598 break;
Mike Stump11289f42009-09-09 15:08:12 +00001599
Douglas Gregorc40290e2009-03-09 23:48:35 +00001600 case TemplateArgument::Expression: {
1601 Expr *E = Arg.getAsExpr();
Douglas Gregor74eba0b2009-06-11 18:10:32 +00001602 TemplateArgument Result;
1603 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
Douglas Gregord32e0282009-02-09 23:23:08 +00001604 Invalid = true;
Douglas Gregor74eba0b2009-06-11 18:10:32 +00001605 else
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001606 Converted.Append(Result);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001607 break;
Douglas Gregord32e0282009-02-09 23:23:08 +00001608 }
1609
Douglas Gregorc40290e2009-03-09 23:48:35 +00001610 case TemplateArgument::Declaration:
1611 case TemplateArgument::Integral:
1612 // We've already checked this template argument, so just copy
1613 // it to the list of converted arguments.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001614 Converted.Append(Arg);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001615 break;
Douglas Gregord32e0282009-02-09 23:23:08 +00001616
Douglas Gregorc40290e2009-03-09 23:48:35 +00001617 case TemplateArgument::Type:
1618 // We have a non-type template parameter but the template
1619 // argument is a type.
Mike Stump11289f42009-09-09 15:08:12 +00001620
Douglas Gregorc40290e2009-03-09 23:48:35 +00001621 // C++ [temp.arg]p2:
1622 // In a template-argument, an ambiguity between a type-id and
1623 // an expression is resolved to a type-id, regardless of the
1624 // form of the corresponding template-parameter.
1625 //
1626 // We warn specifically about this case, since it can be rather
1627 // confusing for users.
1628 if (Arg.getAsType()->isFunctionType())
1629 Diag(Arg.getLocation(), diag::err_template_arg_nontype_ambig)
1630 << Arg.getAsType();
1631 else
1632 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr);
1633 Diag((*Param)->getLocation(), diag::note_template_param_here);
1634 Invalid = true;
Anders Carlssonbc343912009-06-15 17:04:53 +00001635 break;
Mike Stump11289f42009-09-09 15:08:12 +00001636
Anders Carlssonbc343912009-06-15 17:04:53 +00001637 case TemplateArgument::Pack:
1638 assert(0 && "FIXME: Implement!");
1639 break;
Douglas Gregorc40290e2009-03-09 23:48:35 +00001640 }
Mike Stump11289f42009-09-09 15:08:12 +00001641 } else {
Douglas Gregord32e0282009-02-09 23:23:08 +00001642 // Check template template parameters.
Mike Stump11289f42009-09-09 15:08:12 +00001643 TemplateTemplateParmDecl *TempParm
Douglas Gregord32e0282009-02-09 23:23:08 +00001644 = cast<TemplateTemplateParmDecl>(*Param);
Mike Stump11289f42009-09-09 15:08:12 +00001645
Douglas Gregorc40290e2009-03-09 23:48:35 +00001646 switch (Arg.getKind()) {
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001647 case TemplateArgument::Null:
1648 assert(false && "Should never see a NULL template argument here");
1649 break;
Mike Stump11289f42009-09-09 15:08:12 +00001650
Douglas Gregorc40290e2009-03-09 23:48:35 +00001651 case TemplateArgument::Expression: {
1652 Expr *ArgExpr = Arg.getAsExpr();
1653 if (ArgExpr && isa<DeclRefExpr>(ArgExpr) &&
1654 isa<TemplateDecl>(cast<DeclRefExpr>(ArgExpr)->getDecl())) {
1655 if (CheckTemplateArgument(TempParm, cast<DeclRefExpr>(ArgExpr)))
1656 Invalid = true;
Mike Stump11289f42009-09-09 15:08:12 +00001657
Douglas Gregorc40290e2009-03-09 23:48:35 +00001658 // Add the converted template argument.
Mike Stump11289f42009-09-09 15:08:12 +00001659 Decl *D
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00001660 = cast<DeclRefExpr>(ArgExpr)->getDecl()->getCanonicalDecl();
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001661 Converted.Append(TemplateArgument(Arg.getLocation(), D));
Douglas Gregorc40290e2009-03-09 23:48:35 +00001662 continue;
1663 }
1664 }
1665 // fall through
Mike Stump11289f42009-09-09 15:08:12 +00001666
Douglas Gregorc40290e2009-03-09 23:48:35 +00001667 case TemplateArgument::Type: {
1668 // We have a template template parameter but the template
1669 // argument does not refer to a template.
1670 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
1671 Invalid = true;
1672 break;
Douglas Gregord32e0282009-02-09 23:23:08 +00001673 }
1674
Douglas Gregorc40290e2009-03-09 23:48:35 +00001675 case TemplateArgument::Declaration:
1676 // We've already checked this template argument, so just copy
1677 // it to the list of converted arguments.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001678 Converted.Append(Arg);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001679 break;
Mike Stump11289f42009-09-09 15:08:12 +00001680
Douglas Gregorc40290e2009-03-09 23:48:35 +00001681 case TemplateArgument::Integral:
1682 assert(false && "Integral argument with template template parameter");
1683 break;
Mike Stump11289f42009-09-09 15:08:12 +00001684
Anders Carlssonbc343912009-06-15 17:04:53 +00001685 case TemplateArgument::Pack:
1686 assert(0 && "FIXME: Implement!");
1687 break;
Douglas Gregorc40290e2009-03-09 23:48:35 +00001688 }
Douglas Gregord32e0282009-02-09 23:23:08 +00001689 }
1690 }
1691
1692 return Invalid;
1693}
1694
1695/// \brief Check a template argument against its corresponding
1696/// template type parameter.
1697///
1698/// This routine implements the semantics of C++ [temp.arg.type]. It
1699/// returns true if an error occurred, and false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001700bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
Douglas Gregord32e0282009-02-09 23:23:08 +00001701 QualType Arg, SourceLocation ArgLoc) {
1702 // C++ [temp.arg.type]p2:
1703 // A local type, a type with no linkage, an unnamed type or a type
1704 // compounded from any of these types shall not be used as a
1705 // template-argument for a template type-parameter.
1706 //
1707 // FIXME: Perform the recursive and no-linkage type checks.
1708 const TagType *Tag = 0;
John McCall9dd450b2009-09-21 23:43:11 +00001709 if (const EnumType *EnumT = Arg->getAs<EnumType>())
Douglas Gregord32e0282009-02-09 23:23:08 +00001710 Tag = EnumT;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001711 else if (const RecordType *RecordT = Arg->getAs<RecordType>())
Douglas Gregord32e0282009-02-09 23:23:08 +00001712 Tag = RecordT;
1713 if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod())
1714 return Diag(ArgLoc, diag::err_template_arg_local_type)
1715 << QualType(Tag, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001716 else if (Tag && !Tag->getDecl()->getDeclName() &&
Douglas Gregor65b2c4c2009-03-10 18:33:27 +00001717 !Tag->getDecl()->getTypedefForAnonDecl()) {
Douglas Gregord32e0282009-02-09 23:23:08 +00001718 Diag(ArgLoc, diag::err_template_arg_unnamed_type);
1719 Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here);
1720 return true;
1721 }
1722
1723 return false;
1724}
1725
Douglas Gregorccb07762009-02-11 19:52:55 +00001726/// \brief Checks whether the given template argument is the address
1727/// of an object or function according to C++ [temp.arg.nontype]p1.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001728bool Sema::CheckTemplateArgumentAddressOfObjectOrFunction(Expr *Arg,
1729 NamedDecl *&Entity) {
Douglas Gregorccb07762009-02-11 19:52:55 +00001730 bool Invalid = false;
1731
1732 // See through any implicit casts we added to fix the type.
Eli Friedman06ed2a52009-10-20 08:27:19 +00001733 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorccb07762009-02-11 19:52:55 +00001734 Arg = Cast->getSubExpr();
1735
Sebastian Redl576fd422009-05-10 18:38:11 +00001736 // C++0x allows nullptr, and there's no further checking to be done for that.
1737 if (Arg->getType()->isNullPtrType())
1738 return false;
1739
Douglas Gregorccb07762009-02-11 19:52:55 +00001740 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00001741 //
Douglas Gregorccb07762009-02-11 19:52:55 +00001742 // A template-argument for a non-type, non-template
1743 // template-parameter shall be one of: [...]
1744 //
1745 // -- the address of an object or function with external
1746 // linkage, including function templates and function
1747 // template-ids but excluding non-static class members,
1748 // expressed as & id-expression where the & is optional if
1749 // the name refers to a function or array, or if the
1750 // corresponding template-parameter is a reference; or
1751 DeclRefExpr *DRE = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001752
Douglas Gregorccb07762009-02-11 19:52:55 +00001753 // Ignore (and complain about) any excess parentheses.
1754 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
1755 if (!Invalid) {
Mike Stump11289f42009-09-09 15:08:12 +00001756 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00001757 diag::err_template_arg_extra_parens)
1758 << Arg->getSourceRange();
1759 Invalid = true;
1760 }
1761
1762 Arg = Parens->getSubExpr();
1763 }
1764
1765 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
1766 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
1767 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
1768 } else
1769 DRE = dyn_cast<DeclRefExpr>(Arg);
1770
1771 if (!DRE || !isa<ValueDecl>(DRE->getDecl()))
Mike Stump11289f42009-09-09 15:08:12 +00001772 return Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00001773 diag::err_template_arg_not_object_or_func_form)
1774 << Arg->getSourceRange();
1775
1776 // Cannot refer to non-static data members
1777 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl()))
1778 return Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
1779 << Field << Arg->getSourceRange();
1780
1781 // Cannot refer to non-static member functions
1782 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
1783 if (!Method->isStatic())
Mike Stump11289f42009-09-09 15:08:12 +00001784 return Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00001785 diag::err_template_arg_method)
1786 << Method << Arg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00001787
Douglas Gregorccb07762009-02-11 19:52:55 +00001788 // Functions must have external linkage.
1789 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
1790 if (Func->getStorageClass() == FunctionDecl::Static) {
Mike Stump11289f42009-09-09 15:08:12 +00001791 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00001792 diag::err_template_arg_function_not_extern)
1793 << Func << Arg->getSourceRange();
1794 Diag(Func->getLocation(), diag::note_template_arg_internal_object)
1795 << true;
1796 return true;
1797 }
1798
1799 // Okay: we've named a function with external linkage.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001800 Entity = Func;
Douglas Gregorccb07762009-02-11 19:52:55 +00001801 return Invalid;
1802 }
1803
1804 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
1805 if (!Var->hasGlobalStorage()) {
Mike Stump11289f42009-09-09 15:08:12 +00001806 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00001807 diag::err_template_arg_object_not_extern)
1808 << Var << Arg->getSourceRange();
1809 Diag(Var->getLocation(), diag::note_template_arg_internal_object)
1810 << true;
1811 return true;
1812 }
1813
1814 // Okay: we've named an object with external linkage
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001815 Entity = Var;
Douglas Gregorccb07762009-02-11 19:52:55 +00001816 return Invalid;
1817 }
Mike Stump11289f42009-09-09 15:08:12 +00001818
Douglas Gregorccb07762009-02-11 19:52:55 +00001819 // We found something else, but we don't know specifically what it is.
Mike Stump11289f42009-09-09 15:08:12 +00001820 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00001821 diag::err_template_arg_not_object_or_func)
1822 << Arg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00001823 Diag(DRE->getDecl()->getLocation(),
Douglas Gregorccb07762009-02-11 19:52:55 +00001824 diag::note_template_arg_refers_here);
1825 return true;
1826}
1827
1828/// \brief Checks whether the given template argument is a pointer to
1829/// member constant according to C++ [temp.arg.nontype]p1.
Mike Stump11289f42009-09-09 15:08:12 +00001830bool
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001831Sema::CheckTemplateArgumentPointerToMember(Expr *Arg, NamedDecl *&Member) {
Douglas Gregorccb07762009-02-11 19:52:55 +00001832 bool Invalid = false;
1833
1834 // See through any implicit casts we added to fix the type.
Eli Friedman06ed2a52009-10-20 08:27:19 +00001835 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorccb07762009-02-11 19:52:55 +00001836 Arg = Cast->getSubExpr();
1837
Sebastian Redl576fd422009-05-10 18:38:11 +00001838 // C++0x allows nullptr, and there's no further checking to be done for that.
1839 if (Arg->getType()->isNullPtrType())
1840 return false;
1841
Douglas Gregorccb07762009-02-11 19:52:55 +00001842 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00001843 //
Douglas Gregorccb07762009-02-11 19:52:55 +00001844 // A template-argument for a non-type, non-template
1845 // template-parameter shall be one of: [...]
1846 //
1847 // -- a pointer to member expressed as described in 5.3.1.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00001848 DeclRefExpr *DRE = 0;
Douglas Gregorccb07762009-02-11 19:52:55 +00001849
1850 // Ignore (and complain about) any excess parentheses.
1851 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
1852 if (!Invalid) {
Mike Stump11289f42009-09-09 15:08:12 +00001853 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00001854 diag::err_template_arg_extra_parens)
1855 << Arg->getSourceRange();
1856 Invalid = true;
1857 }
1858
1859 Arg = Parens->getSubExpr();
1860 }
1861
1862 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg))
Douglas Gregor4bd90e52009-10-23 18:54:35 +00001863 if (UnOp->getOpcode() == UnaryOperator::AddrOf) {
1864 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
1865 if (DRE && !DRE->getQualifier())
1866 DRE = 0;
1867 }
Douglas Gregorccb07762009-02-11 19:52:55 +00001868
1869 if (!DRE)
1870 return Diag(Arg->getSourceRange().getBegin(),
1871 diag::err_template_arg_not_pointer_to_member_form)
1872 << Arg->getSourceRange();
1873
1874 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
1875 assert((isa<FieldDecl>(DRE->getDecl()) ||
1876 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
1877 "Only non-static member pointers can make it here");
1878
1879 // Okay: this is the address of a non-static member, and therefore
1880 // a member pointer constant.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001881 Member = DRE->getDecl();
Douglas Gregorccb07762009-02-11 19:52:55 +00001882 return Invalid;
1883 }
1884
1885 // We found something else, but we don't know specifically what it is.
Mike Stump11289f42009-09-09 15:08:12 +00001886 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00001887 diag::err_template_arg_not_pointer_to_member_form)
1888 << Arg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00001889 Diag(DRE->getDecl()->getLocation(),
Douglas Gregorccb07762009-02-11 19:52:55 +00001890 diag::note_template_arg_refers_here);
1891 return true;
1892}
1893
Douglas Gregord32e0282009-02-09 23:23:08 +00001894/// \brief Check a template argument against its corresponding
1895/// non-type template parameter.
1896///
Douglas Gregor463421d2009-03-03 04:44:36 +00001897/// This routine implements the semantics of C++ [temp.arg.nontype].
1898/// It returns true if an error occurred, and false otherwise. \p
1899/// InstantiatedParamType is the type of the non-type template
1900/// parameter after it has been instantiated.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001901///
Douglas Gregor74eba0b2009-06-11 18:10:32 +00001902/// If no error was detected, Converted receives the converted template argument.
Douglas Gregord32e0282009-02-09 23:23:08 +00001903bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Mike Stump11289f42009-09-09 15:08:12 +00001904 QualType InstantiatedParamType, Expr *&Arg,
Douglas Gregor74eba0b2009-06-11 18:10:32 +00001905 TemplateArgument &Converted) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00001906 SourceLocation StartLoc = Arg->getSourceRange().getBegin();
1907
Douglas Gregor86560402009-02-10 23:36:10 +00001908 // If either the parameter has a dependent type or the argument is
1909 // type-dependent, there's nothing we can check now.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001910 // FIXME: Add template argument to Converted!
Douglas Gregorc40290e2009-03-09 23:48:35 +00001911 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
1912 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor74eba0b2009-06-11 18:10:32 +00001913 Converted = TemplateArgument(Arg);
Douglas Gregor86560402009-02-10 23:36:10 +00001914 return false;
Douglas Gregorc40290e2009-03-09 23:48:35 +00001915 }
Douglas Gregor86560402009-02-10 23:36:10 +00001916
1917 // C++ [temp.arg.nontype]p5:
1918 // The following conversions are performed on each expression used
1919 // as a non-type template-argument. If a non-type
1920 // template-argument cannot be converted to the type of the
1921 // corresponding template-parameter then the program is
1922 // ill-formed.
1923 //
1924 // -- for a non-type template-parameter of integral or
1925 // enumeration type, integral promotions (4.5) and integral
1926 // conversions (4.7) are applied.
Douglas Gregor463421d2009-03-03 04:44:36 +00001927 QualType ParamType = InstantiatedParamType;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00001928 QualType ArgType = Arg->getType();
Douglas Gregor86560402009-02-10 23:36:10 +00001929 if (ParamType->isIntegralType() || ParamType->isEnumeralType()) {
Douglas Gregor86560402009-02-10 23:36:10 +00001930 // C++ [temp.arg.nontype]p1:
1931 // A template-argument for a non-type, non-template
1932 // template-parameter shall be one of:
1933 //
1934 // -- an integral constant-expression of integral or enumeration
1935 // type; or
1936 // -- the name of a non-type template-parameter; or
1937 SourceLocation NonConstantLoc;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001938 llvm::APSInt Value;
Douglas Gregor86560402009-02-10 23:36:10 +00001939 if (!ArgType->isIntegralType() && !ArgType->isEnumeralType()) {
Mike Stump11289f42009-09-09 15:08:12 +00001940 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor86560402009-02-10 23:36:10 +00001941 diag::err_template_arg_not_integral_or_enumeral)
1942 << ArgType << Arg->getSourceRange();
1943 Diag(Param->getLocation(), diag::note_template_param_here);
1944 return true;
1945 } else if (!Arg->isValueDependent() &&
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001946 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
Douglas Gregor86560402009-02-10 23:36:10 +00001947 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
1948 << ArgType << Arg->getSourceRange();
1949 return true;
1950 }
1951
1952 // FIXME: We need some way to more easily get the unqualified form
1953 // of the types without going all the way to the
1954 // canonical type.
1955 if (Context.getCanonicalType(ParamType).getCVRQualifiers())
1956 ParamType = Context.getCanonicalType(ParamType).getUnqualifiedType();
1957 if (Context.getCanonicalType(ArgType).getCVRQualifiers())
1958 ArgType = Context.getCanonicalType(ArgType).getUnqualifiedType();
1959
1960 // Try to convert the argument to the parameter's type.
1961 if (ParamType == ArgType) {
1962 // Okay: no conversion necessary
1963 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
1964 !ParamType->isEnumeralType()) {
1965 // This is an integral promotion or conversion.
Eli Friedman06ed2a52009-10-20 08:27:19 +00001966 ImpCastExprToType(Arg, ParamType, CastExpr::CK_IntegralCast);
Douglas Gregor86560402009-02-10 23:36:10 +00001967 } else {
1968 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00001969 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor86560402009-02-10 23:36:10 +00001970 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00001971 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor86560402009-02-10 23:36:10 +00001972 Diag(Param->getLocation(), diag::note_template_param_here);
1973 return true;
1974 }
1975
Douglas Gregor52aba872009-03-14 00:20:21 +00001976 QualType IntegerType = Context.getCanonicalType(ParamType);
John McCall9dd450b2009-09-21 23:43:11 +00001977 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
Douglas Gregor74eba0b2009-06-11 18:10:32 +00001978 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregor52aba872009-03-14 00:20:21 +00001979
1980 if (!Arg->isValueDependent()) {
1981 // Check that an unsigned parameter does not receive a negative
1982 // value.
1983 if (IntegerType->isUnsignedIntegerType()
1984 && (Value.isSigned() && Value.isNegative())) {
1985 Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_negative)
1986 << Value.toString(10) << Param->getType()
1987 << Arg->getSourceRange();
1988 Diag(Param->getLocation(), diag::note_template_param_here);
1989 return true;
1990 }
1991
1992 // Check that we don't overflow the template parameter type.
1993 unsigned AllowedBits = Context.getTypeSize(IntegerType);
1994 if (Value.getActiveBits() > AllowedBits) {
Mike Stump11289f42009-09-09 15:08:12 +00001995 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor52aba872009-03-14 00:20:21 +00001996 diag::err_template_arg_too_large)
1997 << Value.toString(10) << Param->getType()
1998 << Arg->getSourceRange();
1999 Diag(Param->getLocation(), diag::note_template_param_here);
2000 return true;
2001 }
2002
2003 if (Value.getBitWidth() != AllowedBits)
2004 Value.extOrTrunc(AllowedBits);
2005 Value.setIsSigned(IntegerType->isSignedIntegerType());
2006 }
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002007
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002008 // Add the value of this argument to the list of converted
2009 // arguments. We use the bitwidth and signedness of the template
2010 // parameter.
2011 if (Arg->isValueDependent()) {
2012 // The argument is value-dependent. Create a new
2013 // TemplateArgument with the converted expression.
2014 Converted = TemplateArgument(Arg);
2015 return false;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002016 }
2017
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002018 Converted = TemplateArgument(StartLoc, Value,
Mike Stump11289f42009-09-09 15:08:12 +00002019 ParamType->isEnumeralType() ? ParamType
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002020 : IntegerType);
Douglas Gregor86560402009-02-10 23:36:10 +00002021 return false;
2022 }
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002023
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002024 // Handle pointer-to-function, reference-to-function, and
2025 // pointer-to-member-function all in (roughly) the same way.
2026 if (// -- For a non-type template-parameter of type pointer to
2027 // function, only the function-to-pointer conversion (4.3) is
2028 // applied. If the template-argument represents a set of
2029 // overloaded functions (or a pointer to such), the matching
2030 // function is selected from the set (13.4).
Sebastian Redl576fd422009-05-10 18:38:11 +00002031 // In C++0x, any std::nullptr_t value can be converted.
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002032 (ParamType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002033 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002034 // -- For a non-type template-parameter of type reference to
2035 // function, no conversions apply. If the template-argument
2036 // represents a set of overloaded functions, the matching
2037 // function is selected from the set (13.4).
2038 (ParamType->isReferenceType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002039 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002040 // -- For a non-type template-parameter of type pointer to
2041 // member function, no conversions apply. If the
2042 // template-argument represents a set of overloaded member
2043 // functions, the matching member function is selected from
2044 // the set (13.4).
Sebastian Redl576fd422009-05-10 18:38:11 +00002045 // Again, C++0x allows a std::nullptr_t value.
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002046 (ParamType->isMemberPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002047 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002048 ->isFunctionType())) {
Mike Stump11289f42009-09-09 15:08:12 +00002049 if (Context.hasSameUnqualifiedType(ArgType,
Douglas Gregorccb07762009-02-11 19:52:55 +00002050 ParamType.getNonReferenceType())) {
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002051 // We don't have to do anything: the types already match.
Sebastian Redl576fd422009-05-10 18:38:11 +00002052 } else if (ArgType->isNullPtrType() && (ParamType->isPointerType() ||
2053 ParamType->isMemberPointerType())) {
2054 ArgType = ParamType;
Eli Friedman06ed2a52009-10-20 08:27:19 +00002055 if (ParamType->isMemberPointerType())
2056 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NullToMemberPointer);
2057 else
2058 ImpCastExprToType(Arg, ParamType, CastExpr::CK_BitCast);
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002059 } else if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002060 ArgType = Context.getPointerType(ArgType);
Eli Friedman06ed2a52009-10-20 08:27:19 +00002061 ImpCastExprToType(Arg, ArgType, CastExpr::CK_FunctionToPointerDecay);
Mike Stump11289f42009-09-09 15:08:12 +00002062 } else if (FunctionDecl *Fn
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002063 = ResolveAddressOfOverloadedFunction(Arg, ParamType, true)) {
Douglas Gregor171c45a2009-02-18 21:56:37 +00002064 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
2065 return true;
2066
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00002067 Arg = FixOverloadedFunctionReference(Arg, Fn);
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002068 ArgType = Arg->getType();
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002069 if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002070 ArgType = Context.getPointerType(Arg->getType());
Eli Friedman06ed2a52009-10-20 08:27:19 +00002071 ImpCastExprToType(Arg, ArgType, CastExpr::CK_FunctionToPointerDecay);
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002072 }
2073 }
2074
Mike Stump11289f42009-09-09 15:08:12 +00002075 if (!Context.hasSameUnqualifiedType(ArgType,
Douglas Gregorccb07762009-02-11 19:52:55 +00002076 ParamType.getNonReferenceType())) {
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002077 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002078 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002079 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002080 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002081 Diag(Param->getLocation(), diag::note_template_param_here);
2082 return true;
2083 }
Mike Stump11289f42009-09-09 15:08:12 +00002084
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002085 if (ParamType->isMemberPointerType()) {
2086 NamedDecl *Member = 0;
2087 if (CheckTemplateArgumentPointerToMember(Arg, Member))
2088 return true;
2089
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002090 if (Member)
2091 Member = cast<NamedDecl>(Member->getCanonicalDecl());
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002092 Converted = TemplateArgument(StartLoc, Member);
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002093 return false;
2094 }
Mike Stump11289f42009-09-09 15:08:12 +00002095
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002096 NamedDecl *Entity = 0;
2097 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2098 return true;
2099
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002100 if (Entity)
2101 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002102 Converted = TemplateArgument(StartLoc, Entity);
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002103 return false;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002104 }
2105
Chris Lattner696197c2009-02-20 21:37:53 +00002106 if (ParamType->isPointerType()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002107 // -- for a non-type template-parameter of type pointer to
2108 // object, qualification conversions (4.4) and the
2109 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl576fd422009-05-10 18:38:11 +00002110 // C++0x also allows a value of std::nullptr_t.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002111 assert(ParamType->getAs<PointerType>()->getPointeeType()->isObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002112 "Only object pointers allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00002113
Sebastian Redl576fd422009-05-10 18:38:11 +00002114 if (ArgType->isNullPtrType()) {
2115 ArgType = ParamType;
Eli Friedman06ed2a52009-10-20 08:27:19 +00002116 ImpCastExprToType(Arg, ParamType, CastExpr::CK_BitCast);
Sebastian Redl576fd422009-05-10 18:38:11 +00002117 } else if (ArgType->isArrayType()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002118 ArgType = Context.getArrayDecayedType(ArgType);
Eli Friedman06ed2a52009-10-20 08:27:19 +00002119 ImpCastExprToType(Arg, ArgType, CastExpr::CK_ArrayToPointerDecay);
Douglas Gregora9faa442009-02-11 00:44:29 +00002120 }
Sebastian Redl576fd422009-05-10 18:38:11 +00002121
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002122 if (IsQualificationConversion(ArgType, ParamType)) {
2123 ArgType = ParamType;
Eli Friedman06ed2a52009-10-20 08:27:19 +00002124 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NoOp);
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002125 }
Mike Stump11289f42009-09-09 15:08:12 +00002126
Douglas Gregor1515f762009-02-11 18:22:40 +00002127 if (!Context.hasSameUnqualifiedType(ArgType, ParamType)) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002128 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002129 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002130 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002131 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002132 Diag(Param->getLocation(), diag::note_template_param_here);
2133 return true;
2134 }
Mike Stump11289f42009-09-09 15:08:12 +00002135
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002136 NamedDecl *Entity = 0;
2137 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2138 return true;
2139
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002140 if (Entity)
2141 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002142 Converted = TemplateArgument(StartLoc, Entity);
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002143 return false;
Douglas Gregora9faa442009-02-11 00:44:29 +00002144 }
Mike Stump11289f42009-09-09 15:08:12 +00002145
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002146 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002147 // -- For a non-type template-parameter of type reference to
2148 // object, no conversions apply. The type referred to by the
2149 // reference may be more cv-qualified than the (otherwise
2150 // identical) type of the template-argument. The
2151 // template-parameter is bound directly to the
2152 // template-argument, which must be an lvalue.
Douglas Gregor64259f52009-03-24 20:32:41 +00002153 assert(ParamRefType->getPointeeType()->isObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002154 "Only object references allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00002155
Douglas Gregor1515f762009-02-11 18:22:40 +00002156 if (!Context.hasSameUnqualifiedType(ParamRefType->getPointeeType(), ArgType)) {
Mike Stump11289f42009-09-09 15:08:12 +00002157 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002158 diag::err_template_arg_no_ref_bind)
Douglas Gregor463421d2009-03-03 04:44:36 +00002159 << InstantiatedParamType << Arg->getType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002160 << Arg->getSourceRange();
2161 Diag(Param->getLocation(), diag::note_template_param_here);
2162 return true;
2163 }
2164
Mike Stump11289f42009-09-09 15:08:12 +00002165 unsigned ParamQuals
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002166 = Context.getCanonicalType(ParamType).getCVRQualifiers();
2167 unsigned ArgQuals = Context.getCanonicalType(ArgType).getCVRQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00002168
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002169 if ((ParamQuals | ArgQuals) != ParamQuals) {
2170 Diag(Arg->getSourceRange().getBegin(),
2171 diag::err_template_arg_ref_bind_ignores_quals)
Douglas Gregor463421d2009-03-03 04:44:36 +00002172 << InstantiatedParamType << Arg->getType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002173 << Arg->getSourceRange();
2174 Diag(Param->getLocation(), diag::note_template_param_here);
2175 return true;
2176 }
Mike Stump11289f42009-09-09 15:08:12 +00002177
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002178 NamedDecl *Entity = 0;
2179 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2180 return true;
2181
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002182 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002183 Converted = TemplateArgument(StartLoc, Entity);
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002184 return false;
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002185 }
Douglas Gregor0e558532009-02-11 16:16:59 +00002186
2187 // -- For a non-type template-parameter of type pointer to data
2188 // member, qualification conversions (4.4) are applied.
Sebastian Redl576fd422009-05-10 18:38:11 +00002189 // C++0x allows std::nullptr_t values.
Douglas Gregor0e558532009-02-11 16:16:59 +00002190 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
2191
Douglas Gregor1515f762009-02-11 18:22:40 +00002192 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
Douglas Gregor0e558532009-02-11 16:16:59 +00002193 // Types match exactly: nothing more to do here.
Sebastian Redl576fd422009-05-10 18:38:11 +00002194 } else if (ArgType->isNullPtrType()) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00002195 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NullToMemberPointer);
Douglas Gregor0e558532009-02-11 16:16:59 +00002196 } else if (IsQualificationConversion(ArgType, ParamType)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00002197 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NoOp);
Douglas Gregor0e558532009-02-11 16:16:59 +00002198 } else {
2199 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002200 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor0e558532009-02-11 16:16:59 +00002201 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002202 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor0e558532009-02-11 16:16:59 +00002203 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00002204 return true;
Douglas Gregor0e558532009-02-11 16:16:59 +00002205 }
2206
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002207 NamedDecl *Member = 0;
2208 if (CheckTemplateArgumentPointerToMember(Arg, Member))
2209 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002210
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002211 if (Member)
2212 Member = cast<NamedDecl>(Member->getCanonicalDecl());
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002213 Converted = TemplateArgument(StartLoc, Member);
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002214 return false;
Douglas Gregord32e0282009-02-09 23:23:08 +00002215}
2216
2217/// \brief Check a template argument against its corresponding
2218/// template template parameter.
2219///
2220/// This routine implements the semantics of C++ [temp.arg.template].
2221/// It returns true if an error occurred, and false otherwise.
2222bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
2223 DeclRefExpr *Arg) {
Douglas Gregor85e0f662009-02-10 00:24:35 +00002224 assert(isa<TemplateDecl>(Arg->getDecl()) && "Only template decls allowed");
2225 TemplateDecl *Template = cast<TemplateDecl>(Arg->getDecl());
2226
2227 // C++ [temp.arg.template]p1:
2228 // A template-argument for a template template-parameter shall be
2229 // the name of a class template, expressed as id-expression. Only
2230 // primary class templates are considered when matching the
2231 // template template argument with the corresponding parameter;
2232 // partial specializations are not considered even if their
2233 // parameter lists match that of the template template parameter.
Douglas Gregord5222052009-06-12 19:43:02 +00002234 //
2235 // Note that we also allow template template parameters here, which
2236 // will happen when we are dealing with, e.g., class template
2237 // partial specializations.
Mike Stump11289f42009-09-09 15:08:12 +00002238 if (!isa<ClassTemplateDecl>(Template) &&
Douglas Gregord5222052009-06-12 19:43:02 +00002239 !isa<TemplateTemplateParmDecl>(Template)) {
Mike Stump11289f42009-09-09 15:08:12 +00002240 assert(isa<FunctionTemplateDecl>(Template) &&
Douglas Gregor85e0f662009-02-10 00:24:35 +00002241 "Only function templates are possible here");
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002242 Diag(Arg->getLocStart(), diag::err_template_arg_not_class_template);
2243 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
Douglas Gregor85e0f662009-02-10 00:24:35 +00002244 << Template;
2245 }
2246
2247 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
2248 Param->getTemplateParameters(),
2249 true, true,
2250 Arg->getSourceRange().getBegin());
Douglas Gregord32e0282009-02-09 23:23:08 +00002251}
2252
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002253/// \brief Determine whether the given template parameter lists are
2254/// equivalent.
2255///
Mike Stump11289f42009-09-09 15:08:12 +00002256/// \param New The new template parameter list, typically written in the
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002257/// source code as part of a new template declaration.
2258///
2259/// \param Old The old template parameter list, typically found via
2260/// name lookup of the template declared with this template parameter
2261/// list.
2262///
2263/// \param Complain If true, this routine will produce a diagnostic if
2264/// the template parameter lists are not equivalent.
2265///
Douglas Gregor85e0f662009-02-10 00:24:35 +00002266/// \param IsTemplateTemplateParm If true, this routine is being
2267/// called to compare the template parameter lists of a template
2268/// template parameter.
2269///
2270/// \param TemplateArgLoc If this source location is valid, then we
2271/// are actually checking the template parameter list of a template
2272/// argument (New) against the template parameter list of its
2273/// corresponding template template parameter (Old). We produce
2274/// slightly different diagnostics in this scenario.
2275///
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002276/// \returns True if the template parameter lists are equal, false
2277/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002278bool
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002279Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
2280 TemplateParameterList *Old,
2281 bool Complain,
Douglas Gregor85e0f662009-02-10 00:24:35 +00002282 bool IsTemplateTemplateParm,
2283 SourceLocation TemplateArgLoc) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002284 if (Old->size() != New->size()) {
2285 if (Complain) {
Douglas Gregor85e0f662009-02-10 00:24:35 +00002286 unsigned NextDiag = diag::err_template_param_list_different_arity;
2287 if (TemplateArgLoc.isValid()) {
2288 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
2289 NextDiag = diag::note_template_param_list_different_arity;
Mike Stump11289f42009-09-09 15:08:12 +00002290 }
Douglas Gregor85e0f662009-02-10 00:24:35 +00002291 Diag(New->getTemplateLoc(), NextDiag)
2292 << (New->size() > Old->size())
2293 << IsTemplateTemplateParm
2294 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002295 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
2296 << IsTemplateTemplateParm
2297 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
2298 }
2299
2300 return false;
2301 }
2302
2303 for (TemplateParameterList::iterator OldParm = Old->begin(),
2304 OldParmEnd = Old->end(), NewParm = New->begin();
2305 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
2306 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
Douglas Gregor23061de2009-06-24 16:50:40 +00002307 if (Complain) {
2308 unsigned NextDiag = diag::err_template_param_different_kind;
2309 if (TemplateArgLoc.isValid()) {
2310 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
2311 NextDiag = diag::note_template_param_different_kind;
2312 }
2313 Diag((*NewParm)->getLocation(), NextDiag)
2314 << IsTemplateTemplateParm;
2315 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
2316 << IsTemplateTemplateParm;
Douglas Gregor85e0f662009-02-10 00:24:35 +00002317 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002318 return false;
2319 }
2320
2321 if (isa<TemplateTypeParmDecl>(*OldParm)) {
2322 // Okay; all template type parameters are equivalent (since we
Douglas Gregor85e0f662009-02-10 00:24:35 +00002323 // know we're at the same index).
2324#if 0
Mike Stump87c57ac2009-05-16 07:39:55 +00002325 // FIXME: Enable this code in debug mode *after* we properly go through
2326 // and "instantiate" the template parameter lists of template template
2327 // parameters. It's only after this instantiation that (1) any dependent
2328 // types within the template parameter list of the template template
2329 // parameter can be checked, and (2) the template type parameter depths
Douglas Gregor85e0f662009-02-10 00:24:35 +00002330 // will match up.
Mike Stump11289f42009-09-09 15:08:12 +00002331 QualType OldParmType
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002332 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*OldParm));
Mike Stump11289f42009-09-09 15:08:12 +00002333 QualType NewParmType
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002334 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*NewParm));
Mike Stump11289f42009-09-09 15:08:12 +00002335 assert(Context.getCanonicalType(OldParmType) ==
2336 Context.getCanonicalType(NewParmType) &&
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002337 "type parameter mismatch?");
2338#endif
Mike Stump11289f42009-09-09 15:08:12 +00002339 } else if (NonTypeTemplateParmDecl *OldNTTP
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002340 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
2341 // The types of non-type template parameters must agree.
2342 NonTypeTemplateParmDecl *NewNTTP
2343 = cast<NonTypeTemplateParmDecl>(*NewParm);
2344 if (Context.getCanonicalType(OldNTTP->getType()) !=
2345 Context.getCanonicalType(NewNTTP->getType())) {
2346 if (Complain) {
Douglas Gregor85e0f662009-02-10 00:24:35 +00002347 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
2348 if (TemplateArgLoc.isValid()) {
Mike Stump11289f42009-09-09 15:08:12 +00002349 Diag(TemplateArgLoc,
Douglas Gregor85e0f662009-02-10 00:24:35 +00002350 diag::err_template_arg_template_params_mismatch);
2351 NextDiag = diag::note_template_nontype_parm_different_type;
2352 }
2353 Diag(NewNTTP->getLocation(), NextDiag)
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002354 << NewNTTP->getType()
2355 << IsTemplateTemplateParm;
Mike Stump11289f42009-09-09 15:08:12 +00002356 Diag(OldNTTP->getLocation(),
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002357 diag::note_template_nontype_parm_prev_declaration)
2358 << OldNTTP->getType();
2359 }
2360 return false;
2361 }
2362 } else {
2363 // The template parameter lists of template template
2364 // parameters must agree.
2365 // FIXME: Could we perform a faster "type" comparison here?
Mike Stump11289f42009-09-09 15:08:12 +00002366 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002367 "Only template template parameters handled here");
Mike Stump11289f42009-09-09 15:08:12 +00002368 TemplateTemplateParmDecl *OldTTP
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002369 = cast<TemplateTemplateParmDecl>(*OldParm);
2370 TemplateTemplateParmDecl *NewTTP
2371 = cast<TemplateTemplateParmDecl>(*NewParm);
2372 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
2373 OldTTP->getTemplateParameters(),
2374 Complain,
Douglas Gregor85e0f662009-02-10 00:24:35 +00002375 /*IsTemplateTemplateParm=*/true,
2376 TemplateArgLoc))
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002377 return false;
2378 }
2379 }
2380
2381 return true;
2382}
2383
2384/// \brief Check whether a template can be declared within this scope.
2385///
2386/// If the template declaration is valid in this scope, returns
2387/// false. Otherwise, issues a diagnostic and returns true.
Mike Stump11289f42009-09-09 15:08:12 +00002388bool
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002389Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002390 // Find the nearest enclosing declaration scope.
2391 while ((S->getFlags() & Scope::DeclScope) == 0 ||
2392 (S->getFlags() & Scope::TemplateParamScope) != 0)
2393 S = S->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00002394
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002395 // C++ [temp]p2:
2396 // A template-declaration can appear only as a namespace scope or
2397 // class scope declaration.
2398 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
Eli Friedmandfbd0c42009-07-31 01:43:05 +00002399 if (Ctx && isa<LinkageSpecDecl>(Ctx) &&
2400 cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
Mike Stump11289f42009-09-09 15:08:12 +00002401 return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002402 << TemplateParams->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002403
Eli Friedmandfbd0c42009-07-31 01:43:05 +00002404 while (Ctx && isa<LinkageSpecDecl>(Ctx))
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002405 Ctx = Ctx->getParent();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002406
2407 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
2408 return false;
2409
Mike Stump11289f42009-09-09 15:08:12 +00002410 return Diag(TemplateParams->getTemplateLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002411 diag::err_template_outside_namespace_or_class_scope)
2412 << TemplateParams->getSourceRange();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002413}
Douglas Gregor67a65642009-02-17 23:15:12 +00002414
Douglas Gregor54888652009-10-07 00:13:32 +00002415/// \brief Determine what kind of template specialization the given declaration
2416/// is.
2417static TemplateSpecializationKind getTemplateSpecializationKind(NamedDecl *D) {
2418 if (!D)
2419 return TSK_Undeclared;
2420
Douglas Gregorbbe8f462009-10-08 15:14:33 +00002421 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
2422 return Record->getTemplateSpecializationKind();
Douglas Gregor54888652009-10-07 00:13:32 +00002423 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
2424 return Function->getTemplateSpecializationKind();
Douglas Gregor86d142a2009-10-08 07:24:58 +00002425 if (VarDecl *Var = dyn_cast<VarDecl>(D))
2426 return Var->getTemplateSpecializationKind();
2427
Douglas Gregor54888652009-10-07 00:13:32 +00002428 return TSK_Undeclared;
2429}
2430
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00002431/// \brief Check whether a specialization is well-formed in the current
2432/// context.
Douglas Gregorf47b9112009-02-25 22:02:03 +00002433///
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00002434/// This routine determines whether a template specialization can be declared
2435/// in the current context (C++ [temp.expl.spec]p2).
Douglas Gregor54888652009-10-07 00:13:32 +00002436///
2437/// \param S the semantic analysis object for which this check is being
2438/// performed.
2439///
2440/// \param Specialized the entity being specialized or instantiated, which
2441/// may be a kind of template (class template, function template, etc.) or
2442/// a member of a class template (member function, static data member,
2443/// member class).
2444///
2445/// \param PrevDecl the previous declaration of this entity, if any.
2446///
2447/// \param Loc the location of the explicit specialization or instantiation of
2448/// this entity.
2449///
2450/// \param IsPartialSpecialization whether this is a partial specialization of
2451/// a class template.
2452///
Douglas Gregor54888652009-10-07 00:13:32 +00002453/// \returns true if there was an error that we cannot recover from, false
2454/// otherwise.
2455static bool CheckTemplateSpecializationScope(Sema &S,
2456 NamedDecl *Specialized,
2457 NamedDecl *PrevDecl,
2458 SourceLocation Loc,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00002459 bool IsPartialSpecialization) {
Douglas Gregor54888652009-10-07 00:13:32 +00002460 // Keep these "kind" numbers in sync with the %select statements in the
2461 // various diagnostics emitted by this routine.
2462 int EntityKind = 0;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00002463 bool isTemplateSpecialization = false;
2464 if (isa<ClassTemplateDecl>(Specialized)) {
Douglas Gregor54888652009-10-07 00:13:32 +00002465 EntityKind = IsPartialSpecialization? 1 : 0;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00002466 isTemplateSpecialization = true;
2467 } else if (isa<FunctionTemplateDecl>(Specialized)) {
Douglas Gregor54888652009-10-07 00:13:32 +00002468 EntityKind = 2;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00002469 isTemplateSpecialization = true;
2470 } else if (isa<CXXMethodDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00002471 EntityKind = 3;
2472 else if (isa<VarDecl>(Specialized))
2473 EntityKind = 4;
2474 else if (isa<RecordDecl>(Specialized))
2475 EntityKind = 5;
2476 else {
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00002477 S.Diag(Loc, diag::err_template_spec_unknown_kind);
2478 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregor54888652009-10-07 00:13:32 +00002479 return true;
2480 }
2481
Douglas Gregorf47b9112009-02-25 22:02:03 +00002482 // C++ [temp.expl.spec]p2:
2483 // An explicit specialization shall be declared in the namespace
2484 // of which the template is a member, or, for member templates, in
2485 // the namespace of which the enclosing class or enclosing class
2486 // template is a member. An explicit specialization of a member
2487 // function, member class or static data member of a class
2488 // template shall be declared in the namespace of which the class
2489 // template is a member. Such a declaration may also be a
2490 // definition. If the declaration is not a definition, the
2491 // specialization may be defined later in the name- space in which
2492 // the explicit specialization was declared, or in a namespace
2493 // that encloses the one in which the explicit specialization was
2494 // declared.
Douglas Gregor54888652009-10-07 00:13:32 +00002495 if (S.CurContext->getLookupContext()->isFunctionOrMethod()) {
2496 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00002497 << Specialized;
Douglas Gregorf47b9112009-02-25 22:02:03 +00002498 return true;
2499 }
Douglas Gregore4b05162009-10-07 17:21:34 +00002500
Douglas Gregor40fb7442009-10-07 17:30:37 +00002501 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
2502 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00002503 << Specialized;
Douglas Gregor40fb7442009-10-07 17:30:37 +00002504 return true;
2505 }
2506
Douglas Gregore4b05162009-10-07 17:21:34 +00002507 // C++ [temp.class.spec]p6:
2508 // A class template partial specialization may be declared or redeclared
2509 // in any namespace scope in which its definition may be defined (14.5.1
2510 // and 14.5.2).
Douglas Gregor54888652009-10-07 00:13:32 +00002511 bool ComplainedAboutScope = false;
Douglas Gregore4b05162009-10-07 17:21:34 +00002512 DeclContext *SpecializedContext
Douglas Gregor54888652009-10-07 00:13:32 +00002513 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregore4b05162009-10-07 17:21:34 +00002514 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00002515 if ((!PrevDecl ||
2516 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
2517 getTemplateSpecializationKind(PrevDecl) == TSK_ImplicitInstantiation)){
2518 // There is no prior declaration of this entity, so this
2519 // specialization must be in the same context as the template
2520 // itself.
2521 if (!DC->Equals(SpecializedContext)) {
2522 if (isa<TranslationUnitDecl>(SpecializedContext))
2523 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global)
2524 << EntityKind << Specialized;
2525 else if (isa<NamespaceDecl>(SpecializedContext))
2526 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope)
2527 << EntityKind << Specialized
2528 << cast<NamedDecl>(SpecializedContext);
2529
2530 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
2531 ComplainedAboutScope = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00002532 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00002533 }
Douglas Gregor54888652009-10-07 00:13:32 +00002534
2535 // Make sure that this redeclaration (or definition) occurs in an enclosing
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00002536 // namespace.
Douglas Gregor54888652009-10-07 00:13:32 +00002537 // Note that HandleDeclarator() performs this check for explicit
2538 // specializations of function templates, static data members, and member
2539 // functions, so we skip the check here for those kinds of entities.
2540 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
Douglas Gregore4b05162009-10-07 17:21:34 +00002541 // Should we refactor that check, so that it occurs later?
2542 if (!ComplainedAboutScope && !DC->Encloses(SpecializedContext) &&
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00002543 !(isa<FunctionTemplateDecl>(Specialized) || isa<VarDecl>(Specialized) ||
2544 isa<FunctionDecl>(Specialized))) {
Douglas Gregor54888652009-10-07 00:13:32 +00002545 if (isa<TranslationUnitDecl>(SpecializedContext))
2546 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
2547 << EntityKind << Specialized;
2548 else if (isa<NamespaceDecl>(SpecializedContext))
2549 S.Diag(Loc, diag::err_template_spec_redecl_out_of_scope)
2550 << EntityKind << Specialized
2551 << cast<NamedDecl>(SpecializedContext);
2552
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00002553 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregorf47b9112009-02-25 22:02:03 +00002554 }
Douglas Gregor54888652009-10-07 00:13:32 +00002555
2556 // FIXME: check for specialization-after-instantiation errors and such.
2557
Douglas Gregorf47b9112009-02-25 22:02:03 +00002558 return false;
2559}
Douglas Gregor54888652009-10-07 00:13:32 +00002560
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002561/// \brief Check the non-type template arguments of a class template
2562/// partial specialization according to C++ [temp.class.spec]p9.
2563///
Douglas Gregor09a30232009-06-12 22:08:06 +00002564/// \param TemplateParams the template parameters of the primary class
2565/// template.
2566///
2567/// \param TemplateArg the template arguments of the class template
2568/// partial specialization.
2569///
2570/// \param MirrorsPrimaryTemplate will be set true if the class
2571/// template partial specialization arguments are identical to the
2572/// implicit template arguments of the primary template. This is not
2573/// necessarily an error (C++0x), and it is left to the caller to diagnose
2574/// this condition when it is an error.
2575///
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002576/// \returns true if there was an error, false otherwise.
2577bool Sema::CheckClassTemplatePartialSpecializationArgs(
2578 TemplateParameterList *TemplateParams,
Anders Carlsson40c1d492009-06-13 18:20:51 +00002579 const TemplateArgumentListBuilder &TemplateArgs,
Douglas Gregor09a30232009-06-12 22:08:06 +00002580 bool &MirrorsPrimaryTemplate) {
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002581 // FIXME: the interface to this function will have to change to
2582 // accommodate variadic templates.
Douglas Gregor09a30232009-06-12 22:08:06 +00002583 MirrorsPrimaryTemplate = true;
Mike Stump11289f42009-09-09 15:08:12 +00002584
Anders Carlsson5947ddf2009-06-23 01:26:57 +00002585 const TemplateArgument *ArgList = TemplateArgs.getFlatArguments();
Mike Stump11289f42009-09-09 15:08:12 +00002586
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002587 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
Douglas Gregor09a30232009-06-12 22:08:06 +00002588 // Determine whether the template argument list of the partial
2589 // specialization is identical to the implicit argument list of
2590 // the primary template. The caller may need to diagnostic this as
2591 // an error per C++ [temp.class.spec]p9b3.
2592 if (MirrorsPrimaryTemplate) {
Mike Stump11289f42009-09-09 15:08:12 +00002593 if (TemplateTypeParmDecl *TTP
Douglas Gregor09a30232009-06-12 22:08:06 +00002594 = dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(I))) {
2595 if (Context.getCanonicalType(Context.getTypeDeclType(TTP)) !=
Anders Carlsson40c1d492009-06-13 18:20:51 +00002596 Context.getCanonicalType(ArgList[I].getAsType()))
Douglas Gregor09a30232009-06-12 22:08:06 +00002597 MirrorsPrimaryTemplate = false;
2598 } else if (TemplateTemplateParmDecl *TTP
2599 = dyn_cast<TemplateTemplateParmDecl>(
2600 TemplateParams->getParam(I))) {
2601 // FIXME: We should settle on either Declaration storage or
2602 // Expression storage for template template parameters.
Mike Stump11289f42009-09-09 15:08:12 +00002603 TemplateTemplateParmDecl *ArgDecl
Douglas Gregor09a30232009-06-12 22:08:06 +00002604 = dyn_cast_or_null<TemplateTemplateParmDecl>(
Anders Carlsson40c1d492009-06-13 18:20:51 +00002605 ArgList[I].getAsDecl());
Douglas Gregor09a30232009-06-12 22:08:06 +00002606 if (!ArgDecl)
Mike Stump11289f42009-09-09 15:08:12 +00002607 if (DeclRefExpr *DRE
Anders Carlsson40c1d492009-06-13 18:20:51 +00002608 = dyn_cast_or_null<DeclRefExpr>(ArgList[I].getAsExpr()))
Douglas Gregor09a30232009-06-12 22:08:06 +00002609 ArgDecl = dyn_cast<TemplateTemplateParmDecl>(DRE->getDecl());
2610
2611 if (!ArgDecl ||
2612 ArgDecl->getIndex() != TTP->getIndex() ||
2613 ArgDecl->getDepth() != TTP->getDepth())
2614 MirrorsPrimaryTemplate = false;
2615 }
2616 }
2617
Mike Stump11289f42009-09-09 15:08:12 +00002618 NonTypeTemplateParmDecl *Param
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002619 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
Douglas Gregor09a30232009-06-12 22:08:06 +00002620 if (!Param) {
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002621 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00002622 }
2623
Anders Carlsson40c1d492009-06-13 18:20:51 +00002624 Expr *ArgExpr = ArgList[I].getAsExpr();
Douglas Gregor09a30232009-06-12 22:08:06 +00002625 if (!ArgExpr) {
2626 MirrorsPrimaryTemplate = false;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002627 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00002628 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002629
2630 // C++ [temp.class.spec]p8:
2631 // A non-type argument is non-specialized if it is the name of a
2632 // non-type parameter. All other non-type arguments are
2633 // specialized.
2634 //
2635 // Below, we check the two conditions that only apply to
2636 // specialized non-type arguments, so skip any non-specialized
2637 // arguments.
2638 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Mike Stump11289f42009-09-09 15:08:12 +00002639 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor09a30232009-06-12 22:08:06 +00002640 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00002641 if (MirrorsPrimaryTemplate &&
Douglas Gregor09a30232009-06-12 22:08:06 +00002642 (Param->getIndex() != NTTP->getIndex() ||
2643 Param->getDepth() != NTTP->getDepth()))
2644 MirrorsPrimaryTemplate = false;
2645
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002646 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00002647 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002648
2649 // C++ [temp.class.spec]p9:
2650 // Within the argument list of a class template partial
2651 // specialization, the following restrictions apply:
2652 // -- A partially specialized non-type argument expression
2653 // shall not involve a template parameter of the partial
2654 // specialization except when the argument expression is a
2655 // simple identifier.
2656 if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
Mike Stump11289f42009-09-09 15:08:12 +00002657 Diag(ArgExpr->getLocStart(),
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002658 diag::err_dependent_non_type_arg_in_partial_spec)
2659 << ArgExpr->getSourceRange();
2660 return true;
2661 }
2662
2663 // -- The type of a template parameter corresponding to a
2664 // specialized non-type argument shall not be dependent on a
2665 // parameter of the specialization.
2666 if (Param->getType()->isDependentType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002667 Diag(ArgExpr->getLocStart(),
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002668 diag::err_dependent_typed_non_type_arg_in_partial_spec)
2669 << Param->getType()
2670 << ArgExpr->getSourceRange();
2671 Diag(Param->getLocation(), diag::note_template_param_here);
2672 return true;
2673 }
Douglas Gregor09a30232009-06-12 22:08:06 +00002674
2675 MirrorsPrimaryTemplate = false;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002676 }
2677
2678 return false;
2679}
2680
Douglas Gregorc08f4892009-03-25 00:13:59 +00002681Sema::DeclResult
John McCall9bb74a52009-07-31 02:45:11 +00002682Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
2683 TagUseKind TUK,
Mike Stump11289f42009-09-09 15:08:12 +00002684 SourceLocation KWLoc,
Douglas Gregor67a65642009-02-17 23:15:12 +00002685 const CXXScopeSpec &SS,
Douglas Gregordc572a32009-03-30 22:58:21 +00002686 TemplateTy TemplateD,
Douglas Gregor67a65642009-02-17 23:15:12 +00002687 SourceLocation TemplateNameLoc,
2688 SourceLocation LAngleLoc,
Douglas Gregorc40290e2009-03-09 23:48:35 +00002689 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregor67a65642009-02-17 23:15:12 +00002690 SourceLocation *TemplateArgLocs,
2691 SourceLocation RAngleLoc,
2692 AttributeList *Attr,
2693 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregor2208a292009-09-26 20:57:03 +00002694 assert(TUK != TUK_Reference && "References are not specializations");
John McCall06f6fe8d2009-09-04 01:14:41 +00002695
Douglas Gregor67a65642009-02-17 23:15:12 +00002696 // Find the class template we're specializing
Douglas Gregordc572a32009-03-30 22:58:21 +00002697 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump11289f42009-09-09 15:08:12 +00002698 ClassTemplateDecl *ClassTemplate
Douglas Gregordc572a32009-03-30 22:58:21 +00002699 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
Douglas Gregor67a65642009-02-17 23:15:12 +00002700
Douglas Gregor5c0405d2009-10-07 22:35:40 +00002701 bool isExplicitSpecialization = false;
Douglas Gregor2373c592009-05-31 09:31:02 +00002702 bool isPartialSpecialization = false;
2703
Douglas Gregorf47b9112009-02-25 22:02:03 +00002704 // Check the validity of the template headers that introduce this
2705 // template.
Douglas Gregor2208a292009-09-26 20:57:03 +00002706 // FIXME: We probably shouldn't complain about these headers for
2707 // friend declarations.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002708 TemplateParameterList *TemplateParams
Mike Stump11289f42009-09-09 15:08:12 +00002709 = MatchTemplateParametersToScopeSpecifier(TemplateNameLoc, SS,
2710 (TemplateParameterList**)TemplateParameterLists.get(),
Douglas Gregor5c0405d2009-10-07 22:35:40 +00002711 TemplateParameterLists.size(),
2712 isExplicitSpecialization);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002713 if (TemplateParams && TemplateParams->size() > 0) {
2714 isPartialSpecialization = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00002715
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002716 // C++ [temp.class.spec]p10:
2717 // The template parameter list of a specialization shall not
2718 // contain default template argument values.
2719 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
2720 Decl *Param = TemplateParams->getParam(I);
2721 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
2722 if (TTP->hasDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00002723 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002724 diag::err_default_arg_in_partial_spec);
2725 TTP->setDefaultArgument(QualType(), SourceLocation(), false);
2726 }
2727 } else if (NonTypeTemplateParmDecl *NTTP
2728 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2729 if (Expr *DefArg = NTTP->getDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00002730 Diag(NTTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002731 diag::err_default_arg_in_partial_spec)
2732 << DefArg->getSourceRange();
2733 NTTP->setDefaultArgument(0);
2734 DefArg->Destroy(Context);
2735 }
2736 } else {
2737 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
2738 if (Expr *DefArg = TTP->getDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00002739 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002740 diag::err_default_arg_in_partial_spec)
2741 << DefArg->getSourceRange();
2742 TTP->setDefaultArgument(0);
2743 DefArg->Destroy(Context);
Douglas Gregord5222052009-06-12 19:43:02 +00002744 }
2745 }
2746 }
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00002747 } else if (TemplateParams) {
2748 if (TUK == TUK_Friend)
2749 Diag(KWLoc, diag::err_template_spec_friend)
2750 << CodeModificationHint::CreateRemoval(
2751 SourceRange(TemplateParams->getTemplateLoc(),
2752 TemplateParams->getRAngleLoc()))
2753 << SourceRange(LAngleLoc, RAngleLoc);
2754 else
2755 isExplicitSpecialization = true;
2756 } else if (TUK != TUK_Friend) {
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002757 Diag(KWLoc, diag::err_template_spec_needs_header)
2758 << CodeModificationHint::CreateInsertion(KWLoc, "template<> ");
Douglas Gregor5c0405d2009-10-07 22:35:40 +00002759 isExplicitSpecialization = true;
2760 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00002761
Douglas Gregor67a65642009-02-17 23:15:12 +00002762 // Check that the specialization uses the same tag kind as the
2763 // original template.
2764 TagDecl::TagKind Kind;
2765 switch (TagSpec) {
2766 default: assert(0 && "Unknown tag type!");
2767 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2768 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2769 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2770 }
Douglas Gregord9034f02009-05-14 16:41:31 +00002771 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump11289f42009-09-09 15:08:12 +00002772 Kind, KWLoc,
Douglas Gregord9034f02009-05-14 16:41:31 +00002773 *ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00002774 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00002775 << ClassTemplate
Mike Stump11289f42009-09-09 15:08:12 +00002776 << CodeModificationHint::CreateReplacement(KWLoc,
Douglas Gregor170512f2009-04-01 23:51:29 +00002777 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00002778 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregor67a65642009-02-17 23:15:12 +00002779 diag::note_previous_use);
2780 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
2781 }
2782
Douglas Gregorc40290e2009-03-09 23:48:35 +00002783 // Translate the parser's template argument list in our AST format.
2784 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
2785 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
2786
Douglas Gregor67a65642009-02-17 23:15:12 +00002787 // Check that the template argument list is well-formed for this
2788 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00002789 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
2790 TemplateArgs.size());
Mike Stump11289f42009-09-09 15:08:12 +00002791 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
Anders Carlsson40c1d492009-06-13 18:20:51 +00002792 TemplateArgs.data(), TemplateArgs.size(),
Douglas Gregore3f1f352009-07-01 00:28:38 +00002793 RAngleLoc, false, Converted))
Douglas Gregorc08f4892009-03-25 00:13:59 +00002794 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00002795
Mike Stump11289f42009-09-09 15:08:12 +00002796 assert((Converted.structuredSize() ==
Douglas Gregor67a65642009-02-17 23:15:12 +00002797 ClassTemplate->getTemplateParameters()->size()) &&
2798 "Converted template argument list is too short!");
Mike Stump11289f42009-09-09 15:08:12 +00002799
Douglas Gregor2373c592009-05-31 09:31:02 +00002800 // Find the class template (partial) specialization declaration that
Douglas Gregor67a65642009-02-17 23:15:12 +00002801 // corresponds to these arguments.
2802 llvm::FoldingSetNodeID ID;
Douglas Gregord5222052009-06-12 19:43:02 +00002803 if (isPartialSpecialization) {
Douglas Gregor09a30232009-06-12 22:08:06 +00002804 bool MirrorsPrimaryTemplate;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002805 if (CheckClassTemplatePartialSpecializationArgs(
2806 ClassTemplate->getTemplateParameters(),
Anders Carlsson5947ddf2009-06-23 01:26:57 +00002807 Converted, MirrorsPrimaryTemplate))
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002808 return true;
2809
Douglas Gregor09a30232009-06-12 22:08:06 +00002810 if (MirrorsPrimaryTemplate) {
2811 // C++ [temp.class.spec]p9b3:
2812 //
Mike Stump11289f42009-09-09 15:08:12 +00002813 // -- The argument list of the specialization shall not be identical
2814 // to the implicit argument list of the primary template.
Douglas Gregor09a30232009-06-12 22:08:06 +00002815 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
John McCall9bb74a52009-07-31 02:45:11 +00002816 << (TUK == TUK_Definition)
Mike Stump11289f42009-09-09 15:08:12 +00002817 << CodeModificationHint::CreateRemoval(SourceRange(LAngleLoc,
Douglas Gregor09a30232009-06-12 22:08:06 +00002818 RAngleLoc));
John McCall9bb74a52009-07-31 02:45:11 +00002819 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
Douglas Gregor09a30232009-06-12 22:08:06 +00002820 ClassTemplate->getIdentifier(),
2821 TemplateNameLoc,
2822 Attr,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002823 TemplateParams,
Douglas Gregor09a30232009-06-12 22:08:06 +00002824 AS_none);
2825 }
2826
Douglas Gregor2208a292009-09-26 20:57:03 +00002827 // FIXME: Diagnose friend partial specializations
2828
Douglas Gregor2373c592009-05-31 09:31:02 +00002829 // FIXME: Template parameter list matters, too
Mike Stump11289f42009-09-09 15:08:12 +00002830 ClassTemplatePartialSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00002831 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00002832 Converted.flatSize(),
2833 Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00002834 } else
Anders Carlsson8aa89d42009-06-05 03:43:12 +00002835 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00002836 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00002837 Converted.flatSize(),
2838 Context);
Douglas Gregor67a65642009-02-17 23:15:12 +00002839 void *InsertPos = 0;
Douglas Gregor2373c592009-05-31 09:31:02 +00002840 ClassTemplateSpecializationDecl *PrevDecl = 0;
2841
2842 if (isPartialSpecialization)
2843 PrevDecl
Mike Stump11289f42009-09-09 15:08:12 +00002844 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
Douglas Gregor2373c592009-05-31 09:31:02 +00002845 InsertPos);
2846 else
2847 PrevDecl
2848 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor67a65642009-02-17 23:15:12 +00002849
2850 ClassTemplateSpecializationDecl *Specialization = 0;
2851
Douglas Gregorf47b9112009-02-25 22:02:03 +00002852 // Check whether we can declare a class template specialization in
2853 // the current scope.
Douglas Gregor2208a292009-09-26 20:57:03 +00002854 if (TUK != TUK_Friend &&
Douglas Gregor54888652009-10-07 00:13:32 +00002855 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00002856 TemplateNameLoc,
2857 isPartialSpecialization))
Douglas Gregorc08f4892009-03-25 00:13:59 +00002858 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00002859
Douglas Gregor15301382009-07-30 17:40:51 +00002860 // The canonical type
2861 QualType CanonType;
Douglas Gregor2208a292009-09-26 20:57:03 +00002862 if (PrevDecl &&
2863 (PrevDecl->getSpecializationKind() == TSK_Undeclared ||
2864 TUK == TUK_Friend)) {
Douglas Gregor67a65642009-02-17 23:15:12 +00002865 // Since the only prior class template specialization with these
Douglas Gregor2208a292009-09-26 20:57:03 +00002866 // arguments was referenced but not declared, or we're only
2867 // referencing this specialization as a friend, reuse that
Douglas Gregor67a65642009-02-17 23:15:12 +00002868 // declaration node as our own, updating its source location to
2869 // reflect our new declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00002870 Specialization = PrevDecl;
Douglas Gregor1e249f82009-02-25 22:18:32 +00002871 Specialization->setLocation(TemplateNameLoc);
Douglas Gregor67a65642009-02-17 23:15:12 +00002872 PrevDecl = 0;
Douglas Gregor15301382009-07-30 17:40:51 +00002873 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregor2373c592009-05-31 09:31:02 +00002874 } else if (isPartialSpecialization) {
Douglas Gregor15301382009-07-30 17:40:51 +00002875 // Build the canonical type that describes the converted template
2876 // arguments of the class template partial specialization.
2877 CanonType = Context.getTemplateSpecializationType(
2878 TemplateName(ClassTemplate),
2879 Converted.getFlatArguments(),
2880 Converted.flatSize());
2881
Douglas Gregor2373c592009-05-31 09:31:02 +00002882 // Create a new class template partial specialization declaration node.
Douglas Gregor2373c592009-05-31 09:31:02 +00002883 ClassTemplatePartialSpecializationDecl *PrevPartial
2884 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
Mike Stump11289f42009-09-09 15:08:12 +00002885 ClassTemplatePartialSpecializationDecl *Partial
2886 = ClassTemplatePartialSpecializationDecl::Create(Context,
Douglas Gregor2373c592009-05-31 09:31:02 +00002887 ClassTemplate->getDeclContext(),
Anders Carlsson1b28c3e2009-06-05 04:06:48 +00002888 TemplateNameLoc,
2889 TemplateParams,
2890 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00002891 Converted,
Anders Carlsson1b28c3e2009-06-05 04:06:48 +00002892 PrevPartial);
Douglas Gregor2373c592009-05-31 09:31:02 +00002893
2894 if (PrevPartial) {
2895 ClassTemplate->getPartialSpecializations().RemoveNode(PrevPartial);
2896 ClassTemplate->getPartialSpecializations().GetOrInsertNode(Partial);
2897 } else {
2898 ClassTemplate->getPartialSpecializations().InsertNode(Partial, InsertPos);
2899 }
2900 Specialization = Partial;
Douglas Gregor91772d12009-06-13 00:26:55 +00002901
Douglas Gregor21610382009-10-29 00:04:11 +00002902 // If we are providing an explicit specialization of a member class
2903 // template specialization, make a note of that.
2904 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
2905 PrevPartial->setMemberSpecialization();
2906
Douglas Gregor91772d12009-06-13 00:26:55 +00002907 // Check that all of the template parameters of the class template
2908 // partial specialization are deducible from the template
2909 // arguments. If not, this class template partial specialization
2910 // will never be used.
2911 llvm::SmallVector<bool, 8> DeducibleParams;
2912 DeducibleParams.resize(TemplateParams->size());
Douglas Gregore1d2ef32009-09-14 21:25:05 +00002913 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
Douglas Gregor21610382009-10-29 00:04:11 +00002914 TemplateParams->getDepth(),
Douglas Gregore1d2ef32009-09-14 21:25:05 +00002915 DeducibleParams);
Douglas Gregor91772d12009-06-13 00:26:55 +00002916 unsigned NumNonDeducible = 0;
2917 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I)
2918 if (!DeducibleParams[I])
2919 ++NumNonDeducible;
2920
2921 if (NumNonDeducible) {
2922 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
2923 << (NumNonDeducible > 1)
2924 << SourceRange(TemplateNameLoc, RAngleLoc);
2925 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
2926 if (!DeducibleParams[I]) {
2927 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
2928 if (Param->getDeclName())
Mike Stump11289f42009-09-09 15:08:12 +00002929 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00002930 diag::note_partial_spec_unused_parameter)
2931 << Param->getDeclName();
2932 else
Mike Stump11289f42009-09-09 15:08:12 +00002933 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00002934 diag::note_partial_spec_unused_parameter)
2935 << std::string("<anonymous>");
2936 }
2937 }
2938 }
Douglas Gregor67a65642009-02-17 23:15:12 +00002939 } else {
2940 // Create a new class template specialization declaration node for
Douglas Gregor2208a292009-09-26 20:57:03 +00002941 // this explicit specialization or friend declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00002942 Specialization
Mike Stump11289f42009-09-09 15:08:12 +00002943 = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregor67a65642009-02-17 23:15:12 +00002944 ClassTemplate->getDeclContext(),
2945 TemplateNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +00002946 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00002947 Converted,
Douglas Gregor67a65642009-02-17 23:15:12 +00002948 PrevDecl);
2949
2950 if (PrevDecl) {
2951 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
2952 ClassTemplate->getSpecializations().GetOrInsertNode(Specialization);
2953 } else {
Mike Stump11289f42009-09-09 15:08:12 +00002954 ClassTemplate->getSpecializations().InsertNode(Specialization,
Douglas Gregor67a65642009-02-17 23:15:12 +00002955 InsertPos);
2956 }
Douglas Gregor15301382009-07-30 17:40:51 +00002957
2958 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00002959 }
2960
Douglas Gregor06db9f52009-10-12 20:18:28 +00002961 // C++ [temp.expl.spec]p6:
2962 // If a template, a member template or the member of a class template is
2963 // explicitly specialized then that specialization shall be declared
2964 // before the first use of that specialization that would cause an implicit
2965 // instantiation to take place, in every translation unit in which such a
2966 // use occurs; no diagnostic is required.
2967 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
2968 SourceRange Range(TemplateNameLoc, RAngleLoc);
2969 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
2970 << Context.getTypeDeclType(Specialization) << Range;
2971
2972 Diag(PrevDecl->getPointOfInstantiation(),
2973 diag::note_instantiation_required_here)
2974 << (PrevDecl->getTemplateSpecializationKind()
2975 != TSK_ImplicitInstantiation);
2976 return true;
2977 }
2978
Douglas Gregor2208a292009-09-26 20:57:03 +00002979 // If this is not a friend, note that this is an explicit specialization.
2980 if (TUK != TUK_Friend)
2981 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00002982
2983 // Check that this isn't a redefinition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00002984 if (TUK == TUK_Definition) {
Douglas Gregor67a65642009-02-17 23:15:12 +00002985 if (RecordDecl *Def = Specialization->getDefinition(Context)) {
Douglas Gregor67a65642009-02-17 23:15:12 +00002986 SourceRange Range(TemplateNameLoc, RAngleLoc);
Mike Stump11289f42009-09-09 15:08:12 +00002987 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregor2373c592009-05-31 09:31:02 +00002988 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregor67a65642009-02-17 23:15:12 +00002989 Diag(Def->getLocation(), diag::note_previous_definition);
2990 Specialization->setInvalidDecl();
Douglas Gregorc08f4892009-03-25 00:13:59 +00002991 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00002992 }
2993 }
2994
Douglas Gregord56a91e2009-02-26 22:19:44 +00002995 // Build the fully-sugared type for this class template
2996 // specialization as the user wrote in the specialization
2997 // itself. This means that we'll pretty-print the type retrieved
2998 // from the specialization's declaration the way that the user
2999 // actually wrote the specialization, rather than formatting the
3000 // name based on the "canonical" representation used to store the
3001 // template arguments in the specialization.
Mike Stump11289f42009-09-09 15:08:12 +00003002 QualType WrittenTy
3003 = Context.getTemplateSpecializationType(Name,
Anders Carlsson40c1d492009-06-13 18:20:51 +00003004 TemplateArgs.data(),
Douglas Gregordc572a32009-03-30 22:58:21 +00003005 TemplateArgs.size(),
Douglas Gregor15301382009-07-30 17:40:51 +00003006 CanonType);
Douglas Gregor2208a292009-09-26 20:57:03 +00003007 if (TUK != TUK_Friend)
3008 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregorc40290e2009-03-09 23:48:35 +00003009 TemplateArgsIn.release();
Douglas Gregor67a65642009-02-17 23:15:12 +00003010
Douglas Gregor1e249f82009-02-25 22:18:32 +00003011 // C++ [temp.expl.spec]p9:
3012 // A template explicit specialization is in the scope of the
3013 // namespace in which the template was defined.
3014 //
3015 // We actually implement this paragraph where we set the semantic
3016 // context (in the creation of the ClassTemplateSpecializationDecl),
3017 // but we also maintain the lexical context where the actual
3018 // definition occurs.
Douglas Gregor67a65642009-02-17 23:15:12 +00003019 Specialization->setLexicalDeclContext(CurContext);
Mike Stump11289f42009-09-09 15:08:12 +00003020
Douglas Gregor67a65642009-02-17 23:15:12 +00003021 // We may be starting the definition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00003022 if (TUK == TUK_Definition)
Douglas Gregor67a65642009-02-17 23:15:12 +00003023 Specialization->startDefinition();
3024
Douglas Gregor2208a292009-09-26 20:57:03 +00003025 if (TUK == TUK_Friend) {
3026 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
3027 TemplateNameLoc,
3028 WrittenTy.getTypePtr(),
3029 /*FIXME:*/KWLoc);
3030 Friend->setAccess(AS_public);
3031 CurContext->addDecl(Friend);
3032 } else {
3033 // Add the specialization into its lexical context, so that it can
3034 // be seen when iterating through the list of declarations in that
3035 // context. However, specializations are not found by name lookup.
3036 CurContext->addDecl(Specialization);
3037 }
Chris Lattner83f095c2009-03-28 19:18:32 +00003038 return DeclPtrTy::make(Specialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00003039}
Douglas Gregor333489b2009-03-27 23:10:48 +00003040
Mike Stump11289f42009-09-09 15:08:12 +00003041Sema::DeclPtrTy
3042Sema::ActOnTemplateDeclarator(Scope *S,
Douglas Gregorb52fabb2009-06-23 23:11:28 +00003043 MultiTemplateParamsArg TemplateParameterLists,
3044 Declarator &D) {
3045 return HandleDeclarator(S, D, move(TemplateParameterLists), false);
3046}
3047
Mike Stump11289f42009-09-09 15:08:12 +00003048Sema::DeclPtrTy
3049Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
Douglas Gregor17a7c122009-06-24 00:54:41 +00003050 MultiTemplateParamsArg TemplateParameterLists,
3051 Declarator &D) {
3052 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
3053 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
3054 "Not a function declarator!");
3055 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Mike Stump11289f42009-09-09 15:08:12 +00003056
Douglas Gregor17a7c122009-06-24 00:54:41 +00003057 if (FTI.hasPrototype) {
Mike Stump11289f42009-09-09 15:08:12 +00003058 // FIXME: Diagnose arguments without names in C.
Douglas Gregor17a7c122009-06-24 00:54:41 +00003059 }
Mike Stump11289f42009-09-09 15:08:12 +00003060
Douglas Gregor17a7c122009-06-24 00:54:41 +00003061 Scope *ParentScope = FnBodyScope->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00003062
3063 DeclPtrTy DP = HandleDeclarator(ParentScope, D,
Douglas Gregor17a7c122009-06-24 00:54:41 +00003064 move(TemplateParameterLists),
3065 /*IsFunctionDefinition=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00003066 if (FunctionTemplateDecl *FunctionTemplate
Douglas Gregord8d297c2009-07-21 23:53:31 +00003067 = dyn_cast_or_null<FunctionTemplateDecl>(DP.getAs<Decl>()))
Mike Stump11289f42009-09-09 15:08:12 +00003068 return ActOnStartOfFunctionDef(FnBodyScope,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003069 DeclPtrTy::make(FunctionTemplate->getTemplatedDecl()));
Douglas Gregord8d297c2009-07-21 23:53:31 +00003070 if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(DP.getAs<Decl>()))
3071 return ActOnStartOfFunctionDef(FnBodyScope, DeclPtrTy::make(Function));
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003072 return DeclPtrTy();
Douglas Gregor17a7c122009-06-24 00:54:41 +00003073}
3074
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003075/// \brief Diagnose cases where we have an explicit template specialization
3076/// before/after an explicit template instantiation, producing diagnostics
3077/// for those cases where they are required and determining whether the
3078/// new specialization/instantiation will have any effect.
3079///
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003080/// \param NewLoc the location of the new explicit specialization or
3081/// instantiation.
3082///
3083/// \param NewTSK the kind of the new explicit specialization or instantiation.
3084///
3085/// \param PrevDecl the previous declaration of the entity.
3086///
3087/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
3088///
3089/// \param PrevPointOfInstantiation if valid, indicates where the previus
3090/// declaration was instantiated (either implicitly or explicitly).
3091///
3092/// \param SuppressNew will be set to true to indicate that the new
3093/// specialization or instantiation has no effect and should be ignored.
3094///
3095/// \returns true if there was an error that should prevent the introduction of
3096/// the new declaration into the AST, false otherwise.
Douglas Gregor1d957a32009-10-27 18:42:08 +00003097bool
3098Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
3099 TemplateSpecializationKind NewTSK,
3100 NamedDecl *PrevDecl,
3101 TemplateSpecializationKind PrevTSK,
3102 SourceLocation PrevPointOfInstantiation,
3103 bool &SuppressNew) {
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003104 SuppressNew = false;
3105
3106 switch (NewTSK) {
3107 case TSK_Undeclared:
3108 case TSK_ImplicitInstantiation:
3109 assert(false && "Don't check implicit instantiations here");
3110 return false;
3111
3112 case TSK_ExplicitSpecialization:
3113 switch (PrevTSK) {
3114 case TSK_Undeclared:
3115 case TSK_ExplicitSpecialization:
3116 // Okay, we're just specializing something that is either already
3117 // explicitly specialized or has merely been mentioned without any
3118 // instantiation.
3119 return false;
3120
3121 case TSK_ImplicitInstantiation:
3122 if (PrevPointOfInstantiation.isInvalid()) {
3123 // The declaration itself has not actually been instantiated, so it is
3124 // still okay to specialize it.
3125 return false;
3126 }
3127 // Fall through
3128
3129 case TSK_ExplicitInstantiationDeclaration:
3130 case TSK_ExplicitInstantiationDefinition:
3131 assert((PrevTSK == TSK_ImplicitInstantiation ||
3132 PrevPointOfInstantiation.isValid()) &&
3133 "Explicit instantiation without point of instantiation?");
3134
3135 // C++ [temp.expl.spec]p6:
3136 // If a template, a member template or the member of a class template
3137 // is explicitly specialized then that specialization shall be declared
3138 // before the first use of that specialization that would cause an
3139 // implicit instantiation to take place, in every translation unit in
3140 // which such a use occurs; no diagnostic is required.
Douglas Gregor1d957a32009-10-27 18:42:08 +00003141 Diag(NewLoc, diag::err_specialization_after_instantiation)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003142 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00003143 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003144 << (PrevTSK != TSK_ImplicitInstantiation);
3145
3146 return true;
3147 }
3148 break;
3149
3150 case TSK_ExplicitInstantiationDeclaration:
3151 switch (PrevTSK) {
3152 case TSK_ExplicitInstantiationDeclaration:
3153 // This explicit instantiation declaration is redundant (that's okay).
3154 SuppressNew = true;
3155 return false;
3156
3157 case TSK_Undeclared:
3158 case TSK_ImplicitInstantiation:
3159 // We're explicitly instantiating something that may have already been
3160 // implicitly instantiated; that's fine.
3161 return false;
3162
3163 case TSK_ExplicitSpecialization:
3164 // C++0x [temp.explicit]p4:
3165 // For a given set of template parameters, if an explicit instantiation
3166 // of a template appears after a declaration of an explicit
3167 // specialization for that template, the explicit instantiation has no
3168 // effect.
3169 return false;
3170
3171 case TSK_ExplicitInstantiationDefinition:
3172 // C++0x [temp.explicit]p10:
3173 // If an entity is the subject of both an explicit instantiation
3174 // declaration and an explicit instantiation definition in the same
3175 // translation unit, the definition shall follow the declaration.
Douglas Gregor1d957a32009-10-27 18:42:08 +00003176 Diag(NewLoc,
3177 diag::err_explicit_instantiation_declaration_after_definition);
3178 Diag(PrevPointOfInstantiation,
3179 diag::note_explicit_instantiation_definition_here);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003180 assert(PrevPointOfInstantiation.isValid() &&
3181 "Explicit instantiation without point of instantiation?");
3182 SuppressNew = true;
3183 return false;
3184 }
3185 break;
3186
3187 case TSK_ExplicitInstantiationDefinition:
3188 switch (PrevTSK) {
3189 case TSK_Undeclared:
3190 case TSK_ImplicitInstantiation:
3191 // We're explicitly instantiating something that may have already been
3192 // implicitly instantiated; that's fine.
3193 return false;
3194
3195 case TSK_ExplicitSpecialization:
3196 // C++ DR 259, C++0x [temp.explicit]p4:
3197 // For a given set of template parameters, if an explicit
3198 // instantiation of a template appears after a declaration of
3199 // an explicit specialization for that template, the explicit
3200 // instantiation has no effect.
3201 //
3202 // In C++98/03 mode, we only give an extension warning here, because it
3203 // is not not harmful to try to explicitly instantiate something that
3204 // has been explicitly specialized.
Douglas Gregor1d957a32009-10-27 18:42:08 +00003205 if (!getLangOptions().CPlusPlus0x) {
3206 Diag(NewLoc, diag::ext_explicit_instantiation_after_specialization)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003207 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00003208 Diag(PrevDecl->getLocation(),
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003209 diag::note_previous_template_specialization);
3210 }
3211 SuppressNew = true;
3212 return false;
3213
3214 case TSK_ExplicitInstantiationDeclaration:
3215 // We're explicity instantiating a definition for something for which we
3216 // were previously asked to suppress instantiations. That's fine.
3217 return false;
3218
3219 case TSK_ExplicitInstantiationDefinition:
3220 // C++0x [temp.spec]p5:
3221 // For a given template and a given set of template-arguments,
3222 // - an explicit instantiation definition shall appear at most once
3223 // in a program,
Douglas Gregor1d957a32009-10-27 18:42:08 +00003224 Diag(NewLoc, diag::err_explicit_instantiation_duplicate)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003225 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00003226 Diag(PrevPointOfInstantiation,
3227 diag::note_previous_explicit_instantiation);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003228 SuppressNew = true;
3229 return false;
3230 }
3231 break;
3232 }
3233
3234 assert(false && "Missing specialization/instantiation case?");
3235
3236 return false;
3237}
3238
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003239/// \brief Perform semantic analysis for the given function template
3240/// specialization.
3241///
3242/// This routine performs all of the semantic analysis required for an
3243/// explicit function template specialization. On successful completion,
3244/// the function declaration \p FD will become a function template
3245/// specialization.
3246///
3247/// \param FD the function declaration, which will be updated to become a
3248/// function template specialization.
3249///
3250/// \param HasExplicitTemplateArgs whether any template arguments were
3251/// explicitly provided.
3252///
3253/// \param LAngleLoc the location of the left angle bracket ('<'), if
3254/// template arguments were explicitly provided.
3255///
3256/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
3257/// if any.
3258///
3259/// \param NumExplicitTemplateArgs the number of explicitly-provided template
3260/// arguments. This number may be zero even when HasExplicitTemplateArgs is
3261/// true as in, e.g., \c void sort<>(char*, char*);
3262///
3263/// \param RAngleLoc the location of the right angle bracket ('>'), if
3264/// template arguments were explicitly provided.
3265///
3266/// \param PrevDecl the set of declarations that
3267bool
3268Sema::CheckFunctionTemplateSpecialization(FunctionDecl *FD,
3269 bool HasExplicitTemplateArgs,
3270 SourceLocation LAngleLoc,
3271 const TemplateArgument *ExplicitTemplateArgs,
3272 unsigned NumExplicitTemplateArgs,
3273 SourceLocation RAngleLoc,
3274 NamedDecl *&PrevDecl) {
3275 // The set of function template specializations that could match this
3276 // explicit function template specialization.
3277 typedef llvm::SmallVector<FunctionDecl *, 8> CandidateSet;
3278 CandidateSet Candidates;
3279
3280 DeclContext *FDLookupContext = FD->getDeclContext()->getLookupContext();
3281 for (OverloadIterator Ovl(PrevDecl), OvlEnd; Ovl != OvlEnd; ++Ovl) {
3282 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(*Ovl)) {
3283 // Only consider templates found within the same semantic lookup scope as
3284 // FD.
3285 if (!FDLookupContext->Equals(Ovl->getDeclContext()->getLookupContext()))
3286 continue;
3287
3288 // C++ [temp.expl.spec]p11:
3289 // A trailing template-argument can be left unspecified in the
3290 // template-id naming an explicit function template specialization
3291 // provided it can be deduced from the function argument type.
3292 // Perform template argument deduction to determine whether we may be
3293 // specializing this template.
3294 // FIXME: It is somewhat wasteful to build
3295 TemplateDeductionInfo Info(Context);
3296 FunctionDecl *Specialization = 0;
3297 if (TemplateDeductionResult TDK
3298 = DeduceTemplateArguments(FunTmpl, HasExplicitTemplateArgs,
3299 ExplicitTemplateArgs,
3300 NumExplicitTemplateArgs,
3301 FD->getType(),
3302 Specialization,
3303 Info)) {
3304 // FIXME: Template argument deduction failed; record why it failed, so
3305 // that we can provide nifty diagnostics.
3306 (void)TDK;
3307 continue;
3308 }
3309
3310 // Record this candidate.
3311 Candidates.push_back(Specialization);
3312 }
3313 }
3314
Douglas Gregor5de279c2009-09-26 03:41:46 +00003315 // Find the most specialized function template.
3316 FunctionDecl *Specialization = getMostSpecialized(Candidates.data(),
3317 Candidates.size(),
3318 TPOC_Other,
3319 FD->getLocation(),
3320 PartialDiagnostic(diag::err_function_template_spec_no_match)
3321 << FD->getDeclName(),
3322 PartialDiagnostic(diag::err_function_template_spec_ambiguous)
3323 << FD->getDeclName() << HasExplicitTemplateArgs,
3324 PartialDiagnostic(diag::note_function_template_spec_matched));
3325 if (!Specialization)
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003326 return true;
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003327
3328 // FIXME: Check if the prior specialization has a point of instantiation.
Douglas Gregor06db9f52009-10-12 20:18:28 +00003329 // If so, we have run afoul of .
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003330
Douglas Gregor54888652009-10-07 00:13:32 +00003331 // Check the scope of this explicit specialization.
3332 if (CheckTemplateSpecializationScope(*this,
3333 Specialization->getPrimaryTemplate(),
3334 Specialization, FD->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003335 false))
Douglas Gregor54888652009-10-07 00:13:32 +00003336 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00003337
3338 // C++ [temp.expl.spec]p6:
3339 // If a template, a member template or the member of a class template is
Douglas Gregor1d957a32009-10-27 18:42:08 +00003340 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00003341 // before the first use of that specialization that would cause an implicit
3342 // instantiation to take place, in every translation unit in which such a
3343 // use occurs; no diagnostic is required.
3344 FunctionTemplateSpecializationInfo *SpecInfo
3345 = Specialization->getTemplateSpecializationInfo();
3346 assert(SpecInfo && "Function template specialization info missing?");
3347 if (SpecInfo->getPointOfInstantiation().isValid()) {
3348 Diag(FD->getLocation(), diag::err_specialization_after_instantiation)
3349 << FD;
3350 Diag(SpecInfo->getPointOfInstantiation(),
3351 diag::note_instantiation_required_here)
3352 << (Specialization->getTemplateSpecializationKind()
3353 != TSK_ImplicitInstantiation);
3354 return true;
3355 }
Douglas Gregor54888652009-10-07 00:13:32 +00003356
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003357 // Mark the prior declaration as an explicit specialization, so that later
3358 // clients know that this is an explicit specialization.
Douglas Gregor06db9f52009-10-12 20:18:28 +00003359 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003360
3361 // Turn the given function declaration into a function template
3362 // specialization, with the template arguments from the previous
3363 // specialization.
3364 FD->setFunctionTemplateSpecialization(Context,
3365 Specialization->getPrimaryTemplate(),
3366 new (Context) TemplateArgumentList(
3367 *Specialization->getTemplateSpecializationArgs()),
3368 /*InsertPos=*/0,
3369 TSK_ExplicitSpecialization);
3370
3371 // The "previous declaration" for this function template specialization is
3372 // the prior function template specialization.
3373 PrevDecl = Specialization;
3374 return false;
3375}
3376
Douglas Gregor86d142a2009-10-08 07:24:58 +00003377/// \brief Perform semantic analysis for the given non-template member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003378/// specialization.
3379///
3380/// This routine performs all of the semantic analysis required for an
3381/// explicit member function specialization. On successful completion,
3382/// the function declaration \p FD will become a member function
3383/// specialization.
3384///
Douglas Gregor86d142a2009-10-08 07:24:58 +00003385/// \param Member the member declaration, which will be updated to become a
3386/// specialization.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003387///
3388/// \param PrevDecl the set of declarations, one of which may be specialized
3389/// by this function specialization.
3390bool
Douglas Gregor86d142a2009-10-08 07:24:58 +00003391Sema::CheckMemberSpecialization(NamedDecl *Member, NamedDecl *&PrevDecl) {
3392 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
3393
3394 // Try to find the member we are instantiating.
3395 NamedDecl *Instantiation = 0;
3396 NamedDecl *InstantiatedFrom = 0;
Douglas Gregor06db9f52009-10-12 20:18:28 +00003397 MemberSpecializationInfo *MSInfo = 0;
3398
Douglas Gregor86d142a2009-10-08 07:24:58 +00003399 if (!PrevDecl) {
3400 // Nowhere to look anyway.
3401 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
3402 for (OverloadIterator Ovl(PrevDecl), OvlEnd; Ovl != OvlEnd; ++Ovl) {
3403 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*Ovl)) {
3404 if (Context.hasSameType(Function->getType(), Method->getType())) {
3405 Instantiation = Method;
3406 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
Douglas Gregor06db9f52009-10-12 20:18:28 +00003407 MSInfo = Method->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00003408 break;
3409 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003410 }
3411 }
Douglas Gregor86d142a2009-10-08 07:24:58 +00003412 } else if (isa<VarDecl>(Member)) {
3413 if (VarDecl *PrevVar = dyn_cast<VarDecl>(PrevDecl))
3414 if (PrevVar->isStaticDataMember()) {
3415 Instantiation = PrevDecl;
3416 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
Douglas Gregor06db9f52009-10-12 20:18:28 +00003417 MSInfo = PrevVar->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00003418 }
3419 } else if (isa<RecordDecl>(Member)) {
3420 if (CXXRecordDecl *PrevRecord = dyn_cast<CXXRecordDecl>(PrevDecl)) {
3421 Instantiation = PrevDecl;
3422 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
Douglas Gregor06db9f52009-10-12 20:18:28 +00003423 MSInfo = PrevRecord->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00003424 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003425 }
3426
3427 if (!Instantiation) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00003428 // There is no previous declaration that matches. Since member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003429 // specializations are always out-of-line, the caller will complain about
3430 // this mismatch later.
3431 return false;
3432 }
3433
Douglas Gregor86d142a2009-10-08 07:24:58 +00003434 // Make sure that this is a specialization of a member.
3435 if (!InstantiatedFrom) {
3436 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
3437 << Member;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003438 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
3439 return true;
3440 }
3441
Douglas Gregor06db9f52009-10-12 20:18:28 +00003442 // C++ [temp.expl.spec]p6:
3443 // If a template, a member template or the member of a class template is
3444 // explicitly specialized then that spe- cialization shall be declared
3445 // before the first use of that specialization that would cause an implicit
3446 // instantiation to take place, in every translation unit in which such a
3447 // use occurs; no diagnostic is required.
3448 assert(MSInfo && "Member specialization info missing?");
3449 if (MSInfo->getPointOfInstantiation().isValid()) {
3450 Diag(Member->getLocation(), diag::err_specialization_after_instantiation)
3451 << Member;
3452 Diag(MSInfo->getPointOfInstantiation(),
3453 diag::note_instantiation_required_here)
3454 << (MSInfo->getTemplateSpecializationKind() != TSK_ImplicitInstantiation);
3455 return true;
3456 }
3457
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003458 // Check the scope of this explicit specialization.
3459 if (CheckTemplateSpecializationScope(*this,
Douglas Gregor86d142a2009-10-08 07:24:58 +00003460 InstantiatedFrom,
3461 Instantiation, Member->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003462 false))
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003463 return true;
Douglas Gregord801b062009-10-07 23:56:10 +00003464
Douglas Gregor86d142a2009-10-08 07:24:58 +00003465 // Note that this is an explicit instantiation of a member.
Douglas Gregorbbe8f462009-10-08 15:14:33 +00003466 // the original declaration to note that it is an explicit specialization
3467 // (if it was previously an implicit instantiation). This latter step
3468 // makes bookkeeping easier.
Douglas Gregor86d142a2009-10-08 07:24:58 +00003469 if (isa<FunctionDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00003470 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
3471 if (InstantiationFunction->getTemplateSpecializationKind() ==
3472 TSK_ImplicitInstantiation) {
3473 InstantiationFunction->setTemplateSpecializationKind(
3474 TSK_ExplicitSpecialization);
3475 InstantiationFunction->setLocation(Member->getLocation());
3476 }
3477
Douglas Gregor86d142a2009-10-08 07:24:58 +00003478 cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
3479 cast<CXXMethodDecl>(InstantiatedFrom),
3480 TSK_ExplicitSpecialization);
3481 } else if (isa<VarDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00003482 VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
3483 if (InstantiationVar->getTemplateSpecializationKind() ==
3484 TSK_ImplicitInstantiation) {
3485 InstantiationVar->setTemplateSpecializationKind(
3486 TSK_ExplicitSpecialization);
3487 InstantiationVar->setLocation(Member->getLocation());
3488 }
3489
Douglas Gregor86d142a2009-10-08 07:24:58 +00003490 Context.setInstantiatedFromStaticDataMember(cast<VarDecl>(Member),
3491 cast<VarDecl>(InstantiatedFrom),
3492 TSK_ExplicitSpecialization);
3493 } else {
3494 assert(isa<CXXRecordDecl>(Member) && "Only member classes remain");
Douglas Gregorbbe8f462009-10-08 15:14:33 +00003495 CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
3496 if (InstantiationClass->getTemplateSpecializationKind() ==
3497 TSK_ImplicitInstantiation) {
3498 InstantiationClass->setTemplateSpecializationKind(
3499 TSK_ExplicitSpecialization);
3500 InstantiationClass->setLocation(Member->getLocation());
3501 }
3502
Douglas Gregor86d142a2009-10-08 07:24:58 +00003503 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
Douglas Gregorbbe8f462009-10-08 15:14:33 +00003504 cast<CXXRecordDecl>(InstantiatedFrom),
3505 TSK_ExplicitSpecialization);
Douglas Gregor86d142a2009-10-08 07:24:58 +00003506 }
3507
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003508 // Save the caller the trouble of having to figure out which declaration
3509 // this specialization matches.
3510 PrevDecl = Instantiation;
3511 return false;
3512}
3513
Douglas Gregore47f5a72009-10-14 23:41:34 +00003514/// \brief Check the scope of an explicit instantiation.
3515static void CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
3516 SourceLocation InstLoc,
3517 bool WasQualifiedName) {
3518 DeclContext *ExpectedContext
3519 = D->getDeclContext()->getEnclosingNamespaceContext()->getLookupContext();
3520 DeclContext *CurContext = S.CurContext->getLookupContext();
3521
3522 // C++0x [temp.explicit]p2:
3523 // An explicit instantiation shall appear in an enclosing namespace of its
3524 // template.
3525 //
3526 // This is DR275, which we do not retroactively apply to C++98/03.
3527 if (S.getLangOptions().CPlusPlus0x &&
3528 !CurContext->Encloses(ExpectedContext)) {
3529 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ExpectedContext))
3530 S.Diag(InstLoc, diag::err_explicit_instantiation_out_of_scope)
3531 << D << NS;
3532 else
3533 S.Diag(InstLoc, diag::err_explicit_instantiation_must_be_global)
3534 << D;
3535 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
3536 return;
3537 }
3538
3539 // C++0x [temp.explicit]p2:
3540 // If the name declared in the explicit instantiation is an unqualified
3541 // name, the explicit instantiation shall appear in the namespace where
3542 // its template is declared or, if that namespace is inline (7.3.1), any
3543 // namespace from its enclosing namespace set.
3544 if (WasQualifiedName)
3545 return;
3546
3547 if (CurContext->Equals(ExpectedContext))
3548 return;
3549
3550 S.Diag(InstLoc, diag::err_explicit_instantiation_unqualified_wrong_namespace)
3551 << D << ExpectedContext;
3552 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
3553}
3554
3555/// \brief Determine whether the given scope specifier has a template-id in it.
3556static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
3557 if (!SS.isSet())
3558 return false;
3559
3560 // C++0x [temp.explicit]p2:
3561 // If the explicit instantiation is for a member function, a member class
3562 // or a static data member of a class template specialization, the name of
3563 // the class template specialization in the qualified-id for the member
3564 // name shall be a simple-template-id.
3565 //
3566 // C++98 has the same restriction, just worded differently.
3567 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
3568 NNS; NNS = NNS->getPrefix())
3569 if (Type *T = NNS->getAsType())
3570 if (isa<TemplateSpecializationType>(T))
3571 return true;
3572
3573 return false;
3574}
3575
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003576// Explicit instantiation of a class template specialization
Douglas Gregor43e75172009-09-04 06:33:52 +00003577// FIXME: Implement extern template semantics
Douglas Gregora1f49972009-05-13 00:25:59 +00003578Sema::DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00003579Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00003580 SourceLocation ExternLoc,
3581 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00003582 unsigned TagSpec,
Douglas Gregora1f49972009-05-13 00:25:59 +00003583 SourceLocation KWLoc,
3584 const CXXScopeSpec &SS,
3585 TemplateTy TemplateD,
3586 SourceLocation TemplateNameLoc,
3587 SourceLocation LAngleLoc,
3588 ASTTemplateArgsPtr TemplateArgsIn,
3589 SourceLocation *TemplateArgLocs,
3590 SourceLocation RAngleLoc,
3591 AttributeList *Attr) {
3592 // Find the class template we're specializing
3593 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump11289f42009-09-09 15:08:12 +00003594 ClassTemplateDecl *ClassTemplate
Douglas Gregora1f49972009-05-13 00:25:59 +00003595 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
3596
3597 // Check that the specialization uses the same tag kind as the
3598 // original template.
3599 TagDecl::TagKind Kind;
3600 switch (TagSpec) {
3601 default: assert(0 && "Unknown tag type!");
3602 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
3603 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
3604 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
3605 }
Douglas Gregord9034f02009-05-14 16:41:31 +00003606 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump11289f42009-09-09 15:08:12 +00003607 Kind, KWLoc,
Douglas Gregord9034f02009-05-14 16:41:31 +00003608 *ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00003609 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora1f49972009-05-13 00:25:59 +00003610 << ClassTemplate
Mike Stump11289f42009-09-09 15:08:12 +00003611 << CodeModificationHint::CreateReplacement(KWLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00003612 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00003613 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregora1f49972009-05-13 00:25:59 +00003614 diag::note_previous_use);
3615 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
3616 }
3617
Douglas Gregore47f5a72009-10-14 23:41:34 +00003618 // C++0x [temp.explicit]p2:
3619 // There are two forms of explicit instantiation: an explicit instantiation
3620 // definition and an explicit instantiation declaration. An explicit
3621 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor54888652009-10-07 00:13:32 +00003622 TemplateSpecializationKind TSK
3623 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
3624 : TSK_ExplicitInstantiationDeclaration;
3625
Douglas Gregora1f49972009-05-13 00:25:59 +00003626 // Translate the parser's template argument list in our AST format.
3627 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
3628 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
3629
3630 // Check that the template argument list is well-formed for this
3631 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003632 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
3633 TemplateArgs.size());
Mike Stump11289f42009-09-09 15:08:12 +00003634 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
Anders Carlssondd096d82009-06-05 02:12:32 +00003635 TemplateArgs.data(), TemplateArgs.size(),
Douglas Gregore3f1f352009-07-01 00:28:38 +00003636 RAngleLoc, false, Converted))
Douglas Gregora1f49972009-05-13 00:25:59 +00003637 return true;
3638
Mike Stump11289f42009-09-09 15:08:12 +00003639 assert((Converted.structuredSize() ==
Douglas Gregora1f49972009-05-13 00:25:59 +00003640 ClassTemplate->getTemplateParameters()->size()) &&
3641 "Converted template argument list is too short!");
Mike Stump11289f42009-09-09 15:08:12 +00003642
Douglas Gregora1f49972009-05-13 00:25:59 +00003643 // Find the class template specialization declaration that
3644 // corresponds to these arguments.
3645 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00003646 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003647 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00003648 Converted.flatSize(),
3649 Context);
Douglas Gregora1f49972009-05-13 00:25:59 +00003650 void *InsertPos = 0;
3651 ClassTemplateSpecializationDecl *PrevDecl
3652 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
3653
Douglas Gregor54888652009-10-07 00:13:32 +00003654 // C++0x [temp.explicit]p2:
3655 // [...] An explicit instantiation shall appear in an enclosing
3656 // namespace of its template. [...]
3657 //
3658 // This is C++ DR 275.
Douglas Gregore47f5a72009-10-14 23:41:34 +00003659 CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
3660 SS.isSet());
Douglas Gregor54888652009-10-07 00:13:32 +00003661
Douglas Gregora1f49972009-05-13 00:25:59 +00003662 ClassTemplateSpecializationDecl *Specialization = 0;
3663
3664 if (PrevDecl) {
Douglas Gregor12e49d32009-10-15 22:53:21 +00003665 bool SuppressNew = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00003666 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
Douglas Gregor12e49d32009-10-15 22:53:21 +00003667 PrevDecl,
3668 PrevDecl->getSpecializationKind(),
3669 PrevDecl->getPointOfInstantiation(),
3670 SuppressNew))
Douglas Gregora1f49972009-05-13 00:25:59 +00003671 return DeclPtrTy::make(PrevDecl);
Douglas Gregora1f49972009-05-13 00:25:59 +00003672
Douglas Gregor12e49d32009-10-15 22:53:21 +00003673 if (SuppressNew)
Douglas Gregor4aa04b12009-09-11 21:19:12 +00003674 return DeclPtrTy::make(PrevDecl);
Douglas Gregor12e49d32009-10-15 22:53:21 +00003675
Douglas Gregor4aa04b12009-09-11 21:19:12 +00003676 if (PrevDecl->getSpecializationKind() == TSK_ImplicitInstantiation ||
3677 PrevDecl->getSpecializationKind() == TSK_Undeclared) {
3678 // Since the only prior class template specialization with these
3679 // arguments was referenced but not declared, reuse that
3680 // declaration node as our own, updating its source location to
3681 // reflect our new declaration.
3682 Specialization = PrevDecl;
3683 Specialization->setLocation(TemplateNameLoc);
3684 PrevDecl = 0;
3685 }
Douglas Gregor12e49d32009-10-15 22:53:21 +00003686 }
Douglas Gregor4aa04b12009-09-11 21:19:12 +00003687
3688 if (!Specialization) {
Douglas Gregora1f49972009-05-13 00:25:59 +00003689 // Create a new class template specialization declaration node for
3690 // this explicit specialization.
3691 Specialization
Mike Stump11289f42009-09-09 15:08:12 +00003692 = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregora1f49972009-05-13 00:25:59 +00003693 ClassTemplate->getDeclContext(),
3694 TemplateNameLoc,
3695 ClassTemplate,
Douglas Gregor4aa04b12009-09-11 21:19:12 +00003696 Converted, PrevDecl);
Douglas Gregora1f49972009-05-13 00:25:59 +00003697
Douglas Gregor4aa04b12009-09-11 21:19:12 +00003698 if (PrevDecl) {
3699 // Remove the previous declaration from the folding set, since we want
3700 // to introduce a new declaration.
3701 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
3702 ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
3703 }
3704
3705 // Insert the new specialization.
3706 ClassTemplate->getSpecializations().InsertNode(Specialization, InsertPos);
Douglas Gregora1f49972009-05-13 00:25:59 +00003707 }
3708
3709 // Build the fully-sugared type for this explicit instantiation as
3710 // the user wrote in the explicit instantiation itself. This means
3711 // that we'll pretty-print the type retrieved from the
3712 // specialization's declaration the way that the user actually wrote
3713 // the explicit instantiation, rather than formatting the name based
3714 // on the "canonical" representation used to store the template
3715 // arguments in the specialization.
Mike Stump11289f42009-09-09 15:08:12 +00003716 QualType WrittenTy
3717 = Context.getTemplateSpecializationType(Name,
Anders Carlsson03c9e872009-06-05 02:45:24 +00003718 TemplateArgs.data(),
Douglas Gregora1f49972009-05-13 00:25:59 +00003719 TemplateArgs.size(),
3720 Context.getTypeDeclType(Specialization));
3721 Specialization->setTypeAsWritten(WrittenTy);
3722 TemplateArgsIn.release();
3723
3724 // Add the explicit instantiation into its lexical context. However,
3725 // since explicit instantiations are never found by name lookup, we
3726 // just put it into the declaration context directly.
3727 Specialization->setLexicalDeclContext(CurContext);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003728 CurContext->addDecl(Specialization);
Douglas Gregora1f49972009-05-13 00:25:59 +00003729
3730 // C++ [temp.explicit]p3:
Douglas Gregora1f49972009-05-13 00:25:59 +00003731 // A definition of a class template or class member template
3732 // shall be in scope at the point of the explicit instantiation of
3733 // the class template or class member template.
3734 //
3735 // This check comes when we actually try to perform the
3736 // instantiation.
Douglas Gregor12e49d32009-10-15 22:53:21 +00003737 ClassTemplateSpecializationDecl *Def
3738 = cast_or_null<ClassTemplateSpecializationDecl>(
3739 Specialization->getDefinition(Context));
3740 if (!Def)
Douglas Gregoref6ab412009-10-27 06:26:26 +00003741 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
Douglas Gregor1d957a32009-10-27 18:42:08 +00003742
3743 // Instantiate the members of this class template specialization.
3744 Def = cast_or_null<ClassTemplateSpecializationDecl>(
3745 Specialization->getDefinition(Context));
3746 if (Def)
Douglas Gregor12e49d32009-10-15 22:53:21 +00003747 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
Douglas Gregora1f49972009-05-13 00:25:59 +00003748
3749 return DeclPtrTy::make(Specialization);
3750}
3751
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003752// Explicit instantiation of a member class of a class template.
3753Sema::DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00003754Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00003755 SourceLocation ExternLoc,
3756 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00003757 unsigned TagSpec,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003758 SourceLocation KWLoc,
3759 const CXXScopeSpec &SS,
3760 IdentifierInfo *Name,
3761 SourceLocation NameLoc,
3762 AttributeList *Attr) {
3763
Douglas Gregord6ab8742009-05-28 23:31:59 +00003764 bool Owned = false;
John McCall7f41d982009-09-11 04:59:25 +00003765 bool IsDependent = false;
John McCall9bb74a52009-07-31 02:45:11 +00003766 DeclPtrTy TagD = ActOnTag(S, TagSpec, Action::TUK_Reference,
Douglas Gregore93e46c2009-07-22 23:48:44 +00003767 KWLoc, SS, Name, NameLoc, Attr, AS_none,
John McCall7f41d982009-09-11 04:59:25 +00003768 MultiTemplateParamsArg(*this, 0, 0),
3769 Owned, IsDependent);
3770 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
3771
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003772 if (!TagD)
3773 return true;
3774
3775 TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
3776 if (Tag->isEnum()) {
3777 Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
3778 << Context.getTypeDeclType(Tag);
3779 return true;
3780 }
3781
Douglas Gregorb8006faf2009-05-27 17:30:49 +00003782 if (Tag->isInvalidDecl())
3783 return true;
Douglas Gregore47f5a72009-10-14 23:41:34 +00003784
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003785 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
3786 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
3787 if (!Pattern) {
3788 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
3789 << Context.getTypeDeclType(Record);
3790 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
3791 return true;
3792 }
3793
Douglas Gregore47f5a72009-10-14 23:41:34 +00003794 // C++0x [temp.explicit]p2:
3795 // If the explicit instantiation is for a class or member class, the
3796 // elaborated-type-specifier in the declaration shall include a
3797 // simple-template-id.
3798 //
3799 // C++98 has the same restriction, just worded differently.
3800 if (!ScopeSpecifierHasTemplateId(SS))
3801 Diag(TemplateLoc, diag::err_explicit_instantiation_without_qualified_id)
3802 << Record << SS.getRange();
3803
3804 // C++0x [temp.explicit]p2:
3805 // There are two forms of explicit instantiation: an explicit instantiation
3806 // definition and an explicit instantiation declaration. An explicit
3807 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor5d851972009-10-14 21:46:58 +00003808 TemplateSpecializationKind TSK
3809 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
3810 : TSK_ExplicitInstantiationDeclaration;
3811
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003812 // C++0x [temp.explicit]p2:
3813 // [...] An explicit instantiation shall appear in an enclosing
3814 // namespace of its template. [...]
3815 //
3816 // This is C++ DR 275.
Douglas Gregore47f5a72009-10-14 23:41:34 +00003817 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003818
3819 // Verify that it is okay to explicitly instantiate here.
Douglas Gregor8f003d02009-10-15 18:07:02 +00003820 CXXRecordDecl *PrevDecl
3821 = cast_or_null<CXXRecordDecl>(Record->getPreviousDeclaration());
3822 if (!PrevDecl && Record->getDefinition(Context))
3823 PrevDecl = Record;
3824 if (PrevDecl) {
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003825 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
3826 bool SuppressNew = false;
3827 assert(MSInfo && "No member specialization information?");
Douglas Gregor1d957a32009-10-27 18:42:08 +00003828 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003829 PrevDecl,
3830 MSInfo->getTemplateSpecializationKind(),
3831 MSInfo->getPointOfInstantiation(),
3832 SuppressNew))
3833 return true;
3834 if (SuppressNew)
3835 return TagD;
3836 }
3837
Douglas Gregor12e49d32009-10-15 22:53:21 +00003838 CXXRecordDecl *RecordDef
3839 = cast_or_null<CXXRecordDecl>(Record->getDefinition(Context));
3840 if (!RecordDef) {
Douglas Gregor68edf132009-10-15 12:53:22 +00003841 // C++ [temp.explicit]p3:
3842 // A definition of a member class of a class template shall be in scope
3843 // at the point of an explicit instantiation of the member class.
3844 CXXRecordDecl *Def
3845 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition(Context));
3846 if (!Def) {
Douglas Gregora8b89d22009-10-15 14:05:49 +00003847 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
3848 << 0 << Record->getDeclName() << Record->getDeclContext();
Douglas Gregor68edf132009-10-15 12:53:22 +00003849 Diag(Pattern->getLocation(), diag::note_forward_declaration)
3850 << Pattern;
3851 return true;
Douglas Gregor1d957a32009-10-27 18:42:08 +00003852 } else {
3853 if (InstantiateClass(NameLoc, Record, Def,
3854 getTemplateInstantiationArgs(Record),
3855 TSK))
3856 return true;
3857
3858 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition(Context));
3859 if (!RecordDef)
3860 return true;
3861 }
3862 }
3863
3864 // Instantiate all of the members of the class.
3865 InstantiateClassMembers(NameLoc, RecordDef,
3866 getTemplateInstantiationArgs(Record), TSK);
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003867
Mike Stump87c57ac2009-05-16 07:39:55 +00003868 // FIXME: We don't have any representation for explicit instantiations of
3869 // member classes. Such a representation is not needed for compilation, but it
3870 // should be available for clients that want to see all of the declarations in
3871 // the source code.
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003872 return TagD;
3873}
3874
Douglas Gregor450f00842009-09-25 18:43:00 +00003875Sema::DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
3876 SourceLocation ExternLoc,
3877 SourceLocation TemplateLoc,
3878 Declarator &D) {
3879 // Explicit instantiations always require a name.
3880 DeclarationName Name = GetNameForDeclarator(D);
3881 if (!Name) {
3882 if (!D.isInvalidType())
3883 Diag(D.getDeclSpec().getSourceRange().getBegin(),
3884 diag::err_explicit_instantiation_requires_name)
3885 << D.getDeclSpec().getSourceRange()
3886 << D.getSourceRange();
3887
3888 return true;
3889 }
3890
3891 // The scope passed in may not be a decl scope. Zip up the scope tree until
3892 // we find one that is.
3893 while ((S->getFlags() & Scope::DeclScope) == 0 ||
3894 (S->getFlags() & Scope::TemplateParamScope) != 0)
3895 S = S->getParent();
3896
3897 // Determine the type of the declaration.
3898 QualType R = GetTypeForDeclarator(D, S, 0);
3899 if (R.isNull())
3900 return true;
3901
3902 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
3903 // Cannot explicitly instantiate a typedef.
3904 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
3905 << Name;
3906 return true;
3907 }
3908
Douglas Gregor3c74d412009-10-14 20:14:33 +00003909 // C++0x [temp.explicit]p1:
3910 // [...] An explicit instantiation of a function template shall not use the
3911 // inline or constexpr specifiers.
3912 // Presumably, this also applies to member functions of class templates as
3913 // well.
3914 if (D.getDeclSpec().isInlineSpecified() && getLangOptions().CPlusPlus0x)
3915 Diag(D.getDeclSpec().getInlineSpecLoc(),
3916 diag::err_explicit_instantiation_inline)
3917 << CodeModificationHint::CreateRemoval(
3918 SourceRange(D.getDeclSpec().getInlineSpecLoc()));
3919
3920 // FIXME: check for constexpr specifier.
3921
Douglas Gregore47f5a72009-10-14 23:41:34 +00003922 // C++0x [temp.explicit]p2:
3923 // There are two forms of explicit instantiation: an explicit instantiation
3924 // definition and an explicit instantiation declaration. An explicit
3925 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor450f00842009-09-25 18:43:00 +00003926 TemplateSpecializationKind TSK
3927 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
3928 : TSK_ExplicitInstantiationDeclaration;
Douglas Gregore47f5a72009-10-14 23:41:34 +00003929
John McCall9f3059a2009-10-09 21:13:30 +00003930 LookupResult Previous;
3931 LookupParsedName(Previous, S, &D.getCXXScopeSpec(),
3932 Name, LookupOrdinaryName);
Douglas Gregor450f00842009-09-25 18:43:00 +00003933
3934 if (!R->isFunctionType()) {
3935 // C++ [temp.explicit]p1:
3936 // A [...] static data member of a class template can be explicitly
3937 // instantiated from the member definition associated with its class
3938 // template.
3939 if (Previous.isAmbiguous()) {
3940 return DiagnoseAmbiguousLookup(Previous, Name, D.getIdentifierLoc(),
3941 D.getSourceRange());
3942 }
3943
John McCall9f3059a2009-10-09 21:13:30 +00003944 VarDecl *Prev = dyn_cast_or_null<VarDecl>(
3945 Previous.getAsSingleDecl(Context));
Douglas Gregor450f00842009-09-25 18:43:00 +00003946 if (!Prev || !Prev->isStaticDataMember()) {
3947 // We expect to see a data data member here.
3948 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
3949 << Name;
3950 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
3951 P != PEnd; ++P)
John McCall9f3059a2009-10-09 21:13:30 +00003952 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor450f00842009-09-25 18:43:00 +00003953 return true;
3954 }
3955
3956 if (!Prev->getInstantiatedFromStaticDataMember()) {
3957 // FIXME: Check for explicit specialization?
3958 Diag(D.getIdentifierLoc(),
3959 diag::err_explicit_instantiation_data_member_not_instantiated)
3960 << Prev;
3961 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
3962 // FIXME: Can we provide a note showing where this was declared?
3963 return true;
3964 }
3965
Douglas Gregore47f5a72009-10-14 23:41:34 +00003966 // C++0x [temp.explicit]p2:
3967 // If the explicit instantiation is for a member function, a member class
3968 // or a static data member of a class template specialization, the name of
3969 // the class template specialization in the qualified-id for the member
3970 // name shall be a simple-template-id.
3971 //
3972 // C++98 has the same restriction, just worded differently.
3973 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
3974 Diag(D.getIdentifierLoc(),
3975 diag::err_explicit_instantiation_without_qualified_id)
3976 << Prev << D.getCXXScopeSpec().getRange();
3977
3978 // Check the scope of this explicit instantiation.
3979 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
3980
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003981 // Verify that it is okay to explicitly instantiate here.
3982 MemberSpecializationInfo *MSInfo = Prev->getMemberSpecializationInfo();
3983 assert(MSInfo && "Missing static data member specialization info?");
3984 bool SuppressNew = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00003985 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003986 MSInfo->getTemplateSpecializationKind(),
3987 MSInfo->getPointOfInstantiation(),
3988 SuppressNew))
3989 return true;
3990 if (SuppressNew)
3991 return DeclPtrTy();
3992
Douglas Gregor450f00842009-09-25 18:43:00 +00003993 // Instantiate static data member.
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00003994 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregor450f00842009-09-25 18:43:00 +00003995 if (TSK == TSK_ExplicitInstantiationDefinition)
Douglas Gregora8b89d22009-10-15 14:05:49 +00003996 InstantiateStaticDataMemberDefinition(D.getIdentifierLoc(), Prev, false,
3997 /*DefinitionRequired=*/true);
Douglas Gregor450f00842009-09-25 18:43:00 +00003998
3999 // FIXME: Create an ExplicitInstantiation node?
4000 return DeclPtrTy();
4001 }
4002
Douglas Gregor0e876e02009-09-25 23:53:26 +00004003 // If the declarator is a template-id, translate the parser's template
4004 // argument list into our AST format.
Douglas Gregord90fd522009-09-25 21:45:23 +00004005 bool HasExplicitTemplateArgs = false;
4006 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
4007 if (D.getKind() == Declarator::DK_TemplateId) {
4008 TemplateIdAnnotation *TemplateId = D.getTemplateId();
4009 ASTTemplateArgsPtr TemplateArgsPtr(*this,
4010 TemplateId->getTemplateArgs(),
4011 TemplateId->getTemplateArgIsType(),
4012 TemplateId->NumArgs);
4013 translateTemplateArguments(TemplateArgsPtr,
4014 TemplateId->getTemplateArgLocations(),
4015 TemplateArgs);
4016 HasExplicitTemplateArgs = true;
Douglas Gregorf343fd82009-10-01 23:51:25 +00004017 TemplateArgsPtr.release();
Douglas Gregord90fd522009-09-25 21:45:23 +00004018 }
Douglas Gregor0e876e02009-09-25 23:53:26 +00004019
Douglas Gregor450f00842009-09-25 18:43:00 +00004020 // C++ [temp.explicit]p1:
4021 // A [...] function [...] can be explicitly instantiated from its template.
4022 // A member function [...] of a class template can be explicitly
4023 // instantiated from the member definition associated with its class
4024 // template.
Douglas Gregor450f00842009-09-25 18:43:00 +00004025 llvm::SmallVector<FunctionDecl *, 8> Matches;
4026 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
4027 P != PEnd; ++P) {
4028 NamedDecl *Prev = *P;
Douglas Gregord90fd522009-09-25 21:45:23 +00004029 if (!HasExplicitTemplateArgs) {
4030 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
4031 if (Context.hasSameUnqualifiedType(Method->getType(), R)) {
4032 Matches.clear();
4033 Matches.push_back(Method);
4034 break;
4035 }
Douglas Gregor450f00842009-09-25 18:43:00 +00004036 }
4037 }
4038
4039 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
4040 if (!FunTmpl)
4041 continue;
4042
4043 TemplateDeductionInfo Info(Context);
4044 FunctionDecl *Specialization = 0;
4045 if (TemplateDeductionResult TDK
Douglas Gregord90fd522009-09-25 21:45:23 +00004046 = DeduceTemplateArguments(FunTmpl, HasExplicitTemplateArgs,
4047 TemplateArgs.data(), TemplateArgs.size(),
Douglas Gregor450f00842009-09-25 18:43:00 +00004048 R, Specialization, Info)) {
4049 // FIXME: Keep track of almost-matches?
4050 (void)TDK;
4051 continue;
4052 }
4053
4054 Matches.push_back(Specialization);
4055 }
4056
4057 // Find the most specialized function template specialization.
4058 FunctionDecl *Specialization
4059 = getMostSpecialized(Matches.data(), Matches.size(), TPOC_Other,
4060 D.getIdentifierLoc(),
4061 PartialDiagnostic(diag::err_explicit_instantiation_not_known) << Name,
4062 PartialDiagnostic(diag::err_explicit_instantiation_ambiguous) << Name,
4063 PartialDiagnostic(diag::note_explicit_instantiation_candidate));
4064
4065 if (!Specialization)
4066 return true;
4067
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004068 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
Douglas Gregor450f00842009-09-25 18:43:00 +00004069 Diag(D.getIdentifierLoc(),
4070 diag::err_explicit_instantiation_member_function_not_instantiated)
4071 << Specialization
4072 << (Specialization->getTemplateSpecializationKind() ==
4073 TSK_ExplicitSpecialization);
4074 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
4075 return true;
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004076 }
Douglas Gregore47f5a72009-10-14 23:41:34 +00004077
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004078 FunctionDecl *PrevDecl = Specialization->getPreviousDeclaration();
Douglas Gregor8f003d02009-10-15 18:07:02 +00004079 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
4080 PrevDecl = Specialization;
4081
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004082 if (PrevDecl) {
4083 bool SuppressNew = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004084 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004085 PrevDecl,
4086 PrevDecl->getTemplateSpecializationKind(),
4087 PrevDecl->getPointOfInstantiation(),
4088 SuppressNew))
4089 return true;
4090
4091 // FIXME: We may still want to build some representation of this
4092 // explicit specialization.
4093 if (SuppressNew)
4094 return DeclPtrTy();
4095 }
4096
4097 if (TSK == TSK_ExplicitInstantiationDefinition)
4098 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization,
4099 false, /*DefinitionRequired=*/true);
4100
4101 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
4102
Douglas Gregore47f5a72009-10-14 23:41:34 +00004103 // C++0x [temp.explicit]p2:
4104 // If the explicit instantiation is for a member function, a member class
4105 // or a static data member of a class template specialization, the name of
4106 // the class template specialization in the qualified-id for the member
4107 // name shall be a simple-template-id.
4108 //
4109 // C++98 has the same restriction, just worded differently.
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004110 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
Douglas Gregore47f5a72009-10-14 23:41:34 +00004111 if (D.getKind() != Declarator::DK_TemplateId && !FunTmpl &&
4112 D.getCXXScopeSpec().isSet() &&
4113 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
4114 Diag(D.getIdentifierLoc(),
4115 diag::err_explicit_instantiation_without_qualified_id)
4116 << Specialization << D.getCXXScopeSpec().getRange();
4117
4118 CheckExplicitInstantiationScope(*this,
4119 FunTmpl? (NamedDecl *)FunTmpl
4120 : Specialization->getInstantiatedFromMemberFunction(),
4121 D.getIdentifierLoc(),
4122 D.getCXXScopeSpec().isSet());
4123
Douglas Gregor450f00842009-09-25 18:43:00 +00004124 // FIXME: Create some kind of ExplicitInstantiationDecl here.
4125 return DeclPtrTy();
4126}
4127
Douglas Gregor333489b2009-03-27 23:10:48 +00004128Sema::TypeResult
John McCall7f41d982009-09-11 04:59:25 +00004129Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
4130 const CXXScopeSpec &SS, IdentifierInfo *Name,
4131 SourceLocation TagLoc, SourceLocation NameLoc) {
4132 // This has to hold, because SS is expected to be defined.
4133 assert(Name && "Expected a name in a dependent tag");
4134
4135 NestedNameSpecifier *NNS
4136 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
4137 if (!NNS)
4138 return true;
4139
4140 QualType T = CheckTypenameType(NNS, *Name, SourceRange(TagLoc, NameLoc));
4141 if (T.isNull())
4142 return true;
4143
4144 TagDecl::TagKind TagKind = TagDecl::getTagKindForTypeSpec(TagSpec);
4145 QualType ElabType = Context.getElaboratedType(T, TagKind);
4146
4147 return ElabType.getAsOpaquePtr();
4148}
4149
4150Sema::TypeResult
Douglas Gregor333489b2009-03-27 23:10:48 +00004151Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
4152 const IdentifierInfo &II, SourceLocation IdLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00004153 NestedNameSpecifier *NNS
Douglas Gregor333489b2009-03-27 23:10:48 +00004154 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
4155 if (!NNS)
4156 return true;
4157
4158 QualType T = CheckTypenameType(NNS, II, SourceRange(TypenameLoc, IdLoc));
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00004159 if (T.isNull())
4160 return true;
Douglas Gregor333489b2009-03-27 23:10:48 +00004161 return T.getAsOpaquePtr();
4162}
4163
Douglas Gregordce2b622009-04-01 00:28:59 +00004164Sema::TypeResult
4165Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
4166 SourceLocation TemplateLoc, TypeTy *Ty) {
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00004167 QualType T = GetTypeFromParser(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00004168 NestedNameSpecifier *NNS
Douglas Gregordce2b622009-04-01 00:28:59 +00004169 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Mike Stump11289f42009-09-09 15:08:12 +00004170 const TemplateSpecializationType *TemplateId
John McCall9dd450b2009-09-21 23:43:11 +00004171 = T->getAs<TemplateSpecializationType>();
Douglas Gregordce2b622009-04-01 00:28:59 +00004172 assert(TemplateId && "Expected a template specialization type");
4173
Douglas Gregor12bbfe12009-09-02 13:05:45 +00004174 if (computeDeclContext(SS, false)) {
4175 // If we can compute a declaration context, then the "typename"
4176 // keyword was superfluous. Just build a QualifiedNameType to keep
4177 // track of the nested-name-specifier.
Mike Stump11289f42009-09-09 15:08:12 +00004178
Douglas Gregor12bbfe12009-09-02 13:05:45 +00004179 // FIXME: Note that the QualifiedNameType had the "typename" keyword!
4180 return Context.getQualifiedNameType(NNS, T).getAsOpaquePtr();
4181 }
Mike Stump11289f42009-09-09 15:08:12 +00004182
Douglas Gregor12bbfe12009-09-02 13:05:45 +00004183 return Context.getTypenameType(NNS, TemplateId).getAsOpaquePtr();
Douglas Gregordce2b622009-04-01 00:28:59 +00004184}
4185
Douglas Gregor333489b2009-03-27 23:10:48 +00004186/// \brief Build the type that describes a C++ typename specifier,
4187/// e.g., "typename T::type".
4188QualType
4189Sema::CheckTypenameType(NestedNameSpecifier *NNS, const IdentifierInfo &II,
4190 SourceRange Range) {
Douglas Gregorc9f9b862009-05-11 19:58:34 +00004191 CXXRecordDecl *CurrentInstantiation = 0;
4192 if (NNS->isDependent()) {
4193 CurrentInstantiation = getCurrentInstantiationOf(NNS);
Douglas Gregor333489b2009-03-27 23:10:48 +00004194
Douglas Gregorc9f9b862009-05-11 19:58:34 +00004195 // If the nested-name-specifier does not refer to the current
4196 // instantiation, then build a typename type.
4197 if (!CurrentInstantiation)
4198 return Context.getTypenameType(NNS, &II);
Mike Stump11289f42009-09-09 15:08:12 +00004199
Douglas Gregorc707da62009-09-02 13:12:51 +00004200 // The nested-name-specifier refers to the current instantiation, so the
4201 // "typename" keyword itself is superfluous. In C++03, the program is
Mike Stump11289f42009-09-09 15:08:12 +00004202 // actually ill-formed. However, DR 382 (in C++0x CD1) allows such
Douglas Gregorc707da62009-09-02 13:12:51 +00004203 // extraneous "typename" keywords, and we retroactively apply this DR to
4204 // C++03 code.
Douglas Gregorc9f9b862009-05-11 19:58:34 +00004205 }
Douglas Gregor333489b2009-03-27 23:10:48 +00004206
Douglas Gregorc9f9b862009-05-11 19:58:34 +00004207 DeclContext *Ctx = 0;
4208
4209 if (CurrentInstantiation)
4210 Ctx = CurrentInstantiation;
4211 else {
4212 CXXScopeSpec SS;
4213 SS.setScopeRep(NNS);
4214 SS.setRange(Range);
4215 if (RequireCompleteDeclContext(SS))
4216 return QualType();
4217
4218 Ctx = computeDeclContext(SS);
4219 }
Douglas Gregor333489b2009-03-27 23:10:48 +00004220 assert(Ctx && "No declaration context?");
4221
4222 DeclarationName Name(&II);
John McCall9f3059a2009-10-09 21:13:30 +00004223 LookupResult Result;
4224 LookupQualifiedName(Result, Ctx, Name, LookupOrdinaryName, false);
Douglas Gregor333489b2009-03-27 23:10:48 +00004225 unsigned DiagID = 0;
4226 Decl *Referenced = 0;
4227 switch (Result.getKind()) {
4228 case LookupResult::NotFound:
Douglas Gregore40876a2009-10-13 21:16:44 +00004229 DiagID = diag::err_typename_nested_not_found;
Douglas Gregor333489b2009-03-27 23:10:48 +00004230 break;
4231
4232 case LookupResult::Found:
John McCall9f3059a2009-10-09 21:13:30 +00004233 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
Douglas Gregor333489b2009-03-27 23:10:48 +00004234 // We found a type. Build a QualifiedNameType, since the
4235 // typename-specifier was just sugar. FIXME: Tell
4236 // QualifiedNameType that it has a "typename" prefix.
4237 return Context.getQualifiedNameType(NNS, Context.getTypeDeclType(Type));
4238 }
4239
4240 DiagID = diag::err_typename_nested_not_type;
John McCall9f3059a2009-10-09 21:13:30 +00004241 Referenced = Result.getFoundDecl();
Douglas Gregor333489b2009-03-27 23:10:48 +00004242 break;
4243
4244 case LookupResult::FoundOverloaded:
4245 DiagID = diag::err_typename_nested_not_type;
4246 Referenced = *Result.begin();
4247 break;
4248
John McCall6538c932009-10-10 05:48:19 +00004249 case LookupResult::Ambiguous:
Douglas Gregor333489b2009-03-27 23:10:48 +00004250 DiagnoseAmbiguousLookup(Result, Name, Range.getEnd(), Range);
4251 return QualType();
4252 }
4253
4254 // If we get here, it's because name lookup did not find a
4255 // type. Emit an appropriate diagnostic and return an error.
Douglas Gregore40876a2009-10-13 21:16:44 +00004256 Diag(Range.getEnd(), DiagID) << Range << Name << Ctx;
Douglas Gregor333489b2009-03-27 23:10:48 +00004257 if (Referenced)
4258 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
4259 << Name;
4260 return QualType();
4261}
Douglas Gregor15acfb92009-08-06 16:20:37 +00004262
4263namespace {
4264 // See Sema::RebuildTypeInCurrentInstantiation
Mike Stump11289f42009-09-09 15:08:12 +00004265 class VISIBILITY_HIDDEN CurrentInstantiationRebuilder
4266 : public TreeTransform<CurrentInstantiationRebuilder> {
Douglas Gregor15acfb92009-08-06 16:20:37 +00004267 SourceLocation Loc;
4268 DeclarationName Entity;
Mike Stump11289f42009-09-09 15:08:12 +00004269
Douglas Gregor15acfb92009-08-06 16:20:37 +00004270 public:
Mike Stump11289f42009-09-09 15:08:12 +00004271 CurrentInstantiationRebuilder(Sema &SemaRef,
Douglas Gregor15acfb92009-08-06 16:20:37 +00004272 SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00004273 DeclarationName Entity)
4274 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
Douglas Gregor15acfb92009-08-06 16:20:37 +00004275 Loc(Loc), Entity(Entity) { }
Mike Stump11289f42009-09-09 15:08:12 +00004276
4277 /// \brief Determine whether the given type \p T has already been
Douglas Gregor15acfb92009-08-06 16:20:37 +00004278 /// transformed.
4279 ///
4280 /// For the purposes of type reconstruction, a type has already been
4281 /// transformed if it is NULL or if it is not dependent.
4282 bool AlreadyTransformed(QualType T) {
4283 return T.isNull() || !T->isDependentType();
4284 }
Mike Stump11289f42009-09-09 15:08:12 +00004285
4286 /// \brief Returns the location of the entity whose type is being
Douglas Gregor15acfb92009-08-06 16:20:37 +00004287 /// rebuilt.
4288 SourceLocation getBaseLocation() { return Loc; }
Mike Stump11289f42009-09-09 15:08:12 +00004289
Douglas Gregor15acfb92009-08-06 16:20:37 +00004290 /// \brief Returns the name of the entity whose type is being rebuilt.
4291 DeclarationName getBaseEntity() { return Entity; }
Mike Stump11289f42009-09-09 15:08:12 +00004292
Douglas Gregoref6ab412009-10-27 06:26:26 +00004293 /// \brief Sets the "base" location and entity when that
4294 /// information is known based on another transformation.
4295 void setBase(SourceLocation Loc, DeclarationName Entity) {
4296 this->Loc = Loc;
4297 this->Entity = Entity;
4298 }
4299
Douglas Gregor15acfb92009-08-06 16:20:37 +00004300 /// \brief Transforms an expression by returning the expression itself
4301 /// (an identity function).
4302 ///
4303 /// FIXME: This is completely unsafe; we will need to actually clone the
4304 /// expressions.
4305 Sema::OwningExprResult TransformExpr(Expr *E) {
4306 return getSema().Owned(E);
4307 }
Mike Stump11289f42009-09-09 15:08:12 +00004308
Douglas Gregor15acfb92009-08-06 16:20:37 +00004309 /// \brief Transforms a typename type by determining whether the type now
4310 /// refers to a member of the current instantiation, and then
4311 /// type-checking and building a QualifiedNameType (when possible).
John McCall550e0c22009-10-21 00:40:46 +00004312 QualType TransformTypenameType(TypeLocBuilder &TLB, TypenameTypeLoc TL);
4313 QualType TransformTypenameType(TypenameType *T);
Douglas Gregor15acfb92009-08-06 16:20:37 +00004314 };
4315}
4316
Mike Stump11289f42009-09-09 15:08:12 +00004317QualType
John McCall550e0c22009-10-21 00:40:46 +00004318CurrentInstantiationRebuilder::TransformTypenameType(TypeLocBuilder &TLB,
4319 TypenameTypeLoc TL) {
4320 QualType Result = TransformTypenameType(TL.getTypePtr());
4321 if (Result.isNull())
4322 return QualType();
4323
4324 TypenameTypeLoc NewTL = TLB.push<TypenameTypeLoc>(Result);
4325 NewTL.setNameLoc(TL.getNameLoc());
4326
4327 return Result;
4328}
4329
4330QualType
4331CurrentInstantiationRebuilder::TransformTypenameType(TypenameType *T) {
4332
Douglas Gregor15acfb92009-08-06 16:20:37 +00004333 NestedNameSpecifier *NNS
4334 = TransformNestedNameSpecifier(T->getQualifier(),
4335 /*FIXME:*/SourceRange(getBaseLocation()));
4336 if (!NNS)
4337 return QualType();
4338
4339 // If the nested-name-specifier did not change, and we cannot compute the
4340 // context corresponding to the nested-name-specifier, then this
4341 // typename type will not change; exit early.
4342 CXXScopeSpec SS;
4343 SS.setRange(SourceRange(getBaseLocation()));
4344 SS.setScopeRep(NNS);
4345 if (NNS == T->getQualifier() && getSema().computeDeclContext(SS) == 0)
4346 return QualType(T, 0);
Mike Stump11289f42009-09-09 15:08:12 +00004347
4348 // Rebuild the typename type, which will probably turn into a
Douglas Gregor15acfb92009-08-06 16:20:37 +00004349 // QualifiedNameType.
4350 if (const TemplateSpecializationType *TemplateId = T->getTemplateId()) {
Mike Stump11289f42009-09-09 15:08:12 +00004351 QualType NewTemplateId
Douglas Gregor15acfb92009-08-06 16:20:37 +00004352 = TransformType(QualType(TemplateId, 0));
4353 if (NewTemplateId.isNull())
4354 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00004355
Douglas Gregor15acfb92009-08-06 16:20:37 +00004356 if (NNS == T->getQualifier() &&
4357 NewTemplateId == QualType(TemplateId, 0))
4358 return QualType(T, 0);
Mike Stump11289f42009-09-09 15:08:12 +00004359
Douglas Gregor15acfb92009-08-06 16:20:37 +00004360 return getDerived().RebuildTypenameType(NNS, NewTemplateId);
4361 }
Mike Stump11289f42009-09-09 15:08:12 +00004362
Douglas Gregor15acfb92009-08-06 16:20:37 +00004363 return getDerived().RebuildTypenameType(NNS, T->getIdentifier());
4364}
4365
4366/// \brief Rebuilds a type within the context of the current instantiation.
4367///
Mike Stump11289f42009-09-09 15:08:12 +00004368/// The type \p T is part of the type of an out-of-line member definition of
Douglas Gregor15acfb92009-08-06 16:20:37 +00004369/// a class template (or class template partial specialization) that was parsed
Mike Stump11289f42009-09-09 15:08:12 +00004370/// and constructed before we entered the scope of the class template (or
Douglas Gregor15acfb92009-08-06 16:20:37 +00004371/// partial specialization thereof). This routine will rebuild that type now
4372/// that we have entered the declarator's scope, which may produce different
4373/// canonical types, e.g.,
4374///
4375/// \code
4376/// template<typename T>
4377/// struct X {
4378/// typedef T* pointer;
4379/// pointer data();
4380/// };
4381///
4382/// template<typename T>
4383/// typename X<T>::pointer X<T>::data() { ... }
4384/// \endcode
4385///
4386/// Here, the type "typename X<T>::pointer" will be created as a TypenameType,
4387/// since we do not know that we can look into X<T> when we parsed the type.
4388/// This function will rebuild the type, performing the lookup of "pointer"
4389/// in X<T> and returning a QualifiedNameType whose canonical type is the same
4390/// as the canonical type of T*, allowing the return types of the out-of-line
4391/// definition and the declaration to match.
4392QualType Sema::RebuildTypeInCurrentInstantiation(QualType T, SourceLocation Loc,
4393 DeclarationName Name) {
4394 if (T.isNull() || !T->isDependentType())
4395 return T;
Mike Stump11289f42009-09-09 15:08:12 +00004396
Douglas Gregor15acfb92009-08-06 16:20:37 +00004397 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
4398 return Rebuilder.TransformType(T);
Benjamin Kramer854d7de2009-08-11 22:33:06 +00004399}
Douglas Gregorbe999392009-09-15 16:23:51 +00004400
4401/// \brief Produces a formatted string that describes the binding of
4402/// template parameters to template arguments.
4403std::string
4404Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
4405 const TemplateArgumentList &Args) {
4406 std::string Result;
4407
4408 if (!Params || Params->size() == 0)
4409 return Result;
4410
4411 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
4412 if (I == 0)
4413 Result += "[with ";
4414 else
4415 Result += ", ";
4416
4417 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
4418 Result += Id->getName();
4419 } else {
4420 Result += '$';
4421 Result += llvm::utostr(I);
4422 }
4423
4424 Result += " = ";
4425
4426 switch (Args[I].getKind()) {
4427 case TemplateArgument::Null:
4428 Result += "<no value>";
4429 break;
4430
4431 case TemplateArgument::Type: {
4432 std::string TypeStr;
4433 Args[I].getAsType().getAsStringInternal(TypeStr,
4434 Context.PrintingPolicy);
4435 Result += TypeStr;
4436 break;
4437 }
4438
4439 case TemplateArgument::Declaration: {
4440 bool Unnamed = true;
4441 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(Args[I].getAsDecl())) {
4442 if (ND->getDeclName()) {
4443 Unnamed = false;
4444 Result += ND->getNameAsString();
4445 }
4446 }
4447
4448 if (Unnamed) {
4449 Result += "<anonymous>";
4450 }
4451 break;
4452 }
4453
4454 case TemplateArgument::Integral: {
4455 Result += Args[I].getAsIntegral()->toString(10);
4456 break;
4457 }
4458
4459 case TemplateArgument::Expression: {
4460 assert(false && "No expressions in deduced template arguments!");
4461 Result += "<expression>";
4462 break;
4463 }
4464
4465 case TemplateArgument::Pack:
4466 // FIXME: Format template argument packs
4467 Result += "<template argument pack>";
4468 break;
4469 }
4470 }
4471
4472 Result += ']';
4473 return Result;
4474}