blob: 0f223208a938248c3c557eba41274fd8a75c52c2 [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.
1848 QualifiedDeclRefExpr *DRE = 0;
1849
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))
1863 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
1864 DRE = dyn_cast<QualifiedDeclRefExpr>(UnOp->getSubExpr());
1865
1866 if (!DRE)
1867 return Diag(Arg->getSourceRange().getBegin(),
1868 diag::err_template_arg_not_pointer_to_member_form)
1869 << Arg->getSourceRange();
1870
1871 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
1872 assert((isa<FieldDecl>(DRE->getDecl()) ||
1873 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
1874 "Only non-static member pointers can make it here");
1875
1876 // Okay: this is the address of a non-static member, and therefore
1877 // a member pointer constant.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001878 Member = DRE->getDecl();
Douglas Gregorccb07762009-02-11 19:52:55 +00001879 return Invalid;
1880 }
1881
1882 // We found something else, but we don't know specifically what it is.
Mike Stump11289f42009-09-09 15:08:12 +00001883 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00001884 diag::err_template_arg_not_pointer_to_member_form)
1885 << Arg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00001886 Diag(DRE->getDecl()->getLocation(),
Douglas Gregorccb07762009-02-11 19:52:55 +00001887 diag::note_template_arg_refers_here);
1888 return true;
1889}
1890
Douglas Gregord32e0282009-02-09 23:23:08 +00001891/// \brief Check a template argument against its corresponding
1892/// non-type template parameter.
1893///
Douglas Gregor463421d2009-03-03 04:44:36 +00001894/// This routine implements the semantics of C++ [temp.arg.nontype].
1895/// It returns true if an error occurred, and false otherwise. \p
1896/// InstantiatedParamType is the type of the non-type template
1897/// parameter after it has been instantiated.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001898///
Douglas Gregor74eba0b2009-06-11 18:10:32 +00001899/// If no error was detected, Converted receives the converted template argument.
Douglas Gregord32e0282009-02-09 23:23:08 +00001900bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Mike Stump11289f42009-09-09 15:08:12 +00001901 QualType InstantiatedParamType, Expr *&Arg,
Douglas Gregor74eba0b2009-06-11 18:10:32 +00001902 TemplateArgument &Converted) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00001903 SourceLocation StartLoc = Arg->getSourceRange().getBegin();
1904
Douglas Gregor86560402009-02-10 23:36:10 +00001905 // If either the parameter has a dependent type or the argument is
1906 // type-dependent, there's nothing we can check now.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001907 // FIXME: Add template argument to Converted!
Douglas Gregorc40290e2009-03-09 23:48:35 +00001908 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
1909 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor74eba0b2009-06-11 18:10:32 +00001910 Converted = TemplateArgument(Arg);
Douglas Gregor86560402009-02-10 23:36:10 +00001911 return false;
Douglas Gregorc40290e2009-03-09 23:48:35 +00001912 }
Douglas Gregor86560402009-02-10 23:36:10 +00001913
1914 // C++ [temp.arg.nontype]p5:
1915 // The following conversions are performed on each expression used
1916 // as a non-type template-argument. If a non-type
1917 // template-argument cannot be converted to the type of the
1918 // corresponding template-parameter then the program is
1919 // ill-formed.
1920 //
1921 // -- for a non-type template-parameter of integral or
1922 // enumeration type, integral promotions (4.5) and integral
1923 // conversions (4.7) are applied.
Douglas Gregor463421d2009-03-03 04:44:36 +00001924 QualType ParamType = InstantiatedParamType;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00001925 QualType ArgType = Arg->getType();
Douglas Gregor86560402009-02-10 23:36:10 +00001926 if (ParamType->isIntegralType() || ParamType->isEnumeralType()) {
Douglas Gregor86560402009-02-10 23:36:10 +00001927 // C++ [temp.arg.nontype]p1:
1928 // A template-argument for a non-type, non-template
1929 // template-parameter shall be one of:
1930 //
1931 // -- an integral constant-expression of integral or enumeration
1932 // type; or
1933 // -- the name of a non-type template-parameter; or
1934 SourceLocation NonConstantLoc;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001935 llvm::APSInt Value;
Douglas Gregor86560402009-02-10 23:36:10 +00001936 if (!ArgType->isIntegralType() && !ArgType->isEnumeralType()) {
Mike Stump11289f42009-09-09 15:08:12 +00001937 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor86560402009-02-10 23:36:10 +00001938 diag::err_template_arg_not_integral_or_enumeral)
1939 << ArgType << Arg->getSourceRange();
1940 Diag(Param->getLocation(), diag::note_template_param_here);
1941 return true;
1942 } else if (!Arg->isValueDependent() &&
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001943 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
Douglas Gregor86560402009-02-10 23:36:10 +00001944 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
1945 << ArgType << Arg->getSourceRange();
1946 return true;
1947 }
1948
1949 // FIXME: We need some way to more easily get the unqualified form
1950 // of the types without going all the way to the
1951 // canonical type.
1952 if (Context.getCanonicalType(ParamType).getCVRQualifiers())
1953 ParamType = Context.getCanonicalType(ParamType).getUnqualifiedType();
1954 if (Context.getCanonicalType(ArgType).getCVRQualifiers())
1955 ArgType = Context.getCanonicalType(ArgType).getUnqualifiedType();
1956
1957 // Try to convert the argument to the parameter's type.
1958 if (ParamType == ArgType) {
1959 // Okay: no conversion necessary
1960 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
1961 !ParamType->isEnumeralType()) {
1962 // This is an integral promotion or conversion.
Eli Friedman06ed2a52009-10-20 08:27:19 +00001963 ImpCastExprToType(Arg, ParamType, CastExpr::CK_IntegralCast);
Douglas Gregor86560402009-02-10 23:36:10 +00001964 } else {
1965 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00001966 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor86560402009-02-10 23:36:10 +00001967 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00001968 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor86560402009-02-10 23:36:10 +00001969 Diag(Param->getLocation(), diag::note_template_param_here);
1970 return true;
1971 }
1972
Douglas Gregor52aba872009-03-14 00:20:21 +00001973 QualType IntegerType = Context.getCanonicalType(ParamType);
John McCall9dd450b2009-09-21 23:43:11 +00001974 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
Douglas Gregor74eba0b2009-06-11 18:10:32 +00001975 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregor52aba872009-03-14 00:20:21 +00001976
1977 if (!Arg->isValueDependent()) {
1978 // Check that an unsigned parameter does not receive a negative
1979 // value.
1980 if (IntegerType->isUnsignedIntegerType()
1981 && (Value.isSigned() && Value.isNegative())) {
1982 Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_negative)
1983 << Value.toString(10) << Param->getType()
1984 << Arg->getSourceRange();
1985 Diag(Param->getLocation(), diag::note_template_param_here);
1986 return true;
1987 }
1988
1989 // Check that we don't overflow the template parameter type.
1990 unsigned AllowedBits = Context.getTypeSize(IntegerType);
1991 if (Value.getActiveBits() > AllowedBits) {
Mike Stump11289f42009-09-09 15:08:12 +00001992 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor52aba872009-03-14 00:20:21 +00001993 diag::err_template_arg_too_large)
1994 << Value.toString(10) << Param->getType()
1995 << Arg->getSourceRange();
1996 Diag(Param->getLocation(), diag::note_template_param_here);
1997 return true;
1998 }
1999
2000 if (Value.getBitWidth() != AllowedBits)
2001 Value.extOrTrunc(AllowedBits);
2002 Value.setIsSigned(IntegerType->isSignedIntegerType());
2003 }
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002004
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002005 // Add the value of this argument to the list of converted
2006 // arguments. We use the bitwidth and signedness of the template
2007 // parameter.
2008 if (Arg->isValueDependent()) {
2009 // The argument is value-dependent. Create a new
2010 // TemplateArgument with the converted expression.
2011 Converted = TemplateArgument(Arg);
2012 return false;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002013 }
2014
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002015 Converted = TemplateArgument(StartLoc, Value,
Mike Stump11289f42009-09-09 15:08:12 +00002016 ParamType->isEnumeralType() ? ParamType
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002017 : IntegerType);
Douglas Gregor86560402009-02-10 23:36:10 +00002018 return false;
2019 }
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002020
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002021 // Handle pointer-to-function, reference-to-function, and
2022 // pointer-to-member-function all in (roughly) the same way.
2023 if (// -- For a non-type template-parameter of type pointer to
2024 // function, only the function-to-pointer conversion (4.3) is
2025 // applied. If the template-argument represents a set of
2026 // overloaded functions (or a pointer to such), the matching
2027 // function is selected from the set (13.4).
Sebastian Redl576fd422009-05-10 18:38:11 +00002028 // In C++0x, any std::nullptr_t value can be converted.
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002029 (ParamType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002030 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002031 // -- For a non-type template-parameter of type reference to
2032 // function, no conversions apply. If the template-argument
2033 // represents a set of overloaded functions, the matching
2034 // function is selected from the set (13.4).
2035 (ParamType->isReferenceType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002036 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002037 // -- For a non-type template-parameter of type pointer to
2038 // member function, no conversions apply. If the
2039 // template-argument represents a set of overloaded member
2040 // functions, the matching member function is selected from
2041 // the set (13.4).
Sebastian Redl576fd422009-05-10 18:38:11 +00002042 // Again, C++0x allows a std::nullptr_t value.
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002043 (ParamType->isMemberPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002044 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002045 ->isFunctionType())) {
Mike Stump11289f42009-09-09 15:08:12 +00002046 if (Context.hasSameUnqualifiedType(ArgType,
Douglas Gregorccb07762009-02-11 19:52:55 +00002047 ParamType.getNonReferenceType())) {
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002048 // We don't have to do anything: the types already match.
Sebastian Redl576fd422009-05-10 18:38:11 +00002049 } else if (ArgType->isNullPtrType() && (ParamType->isPointerType() ||
2050 ParamType->isMemberPointerType())) {
2051 ArgType = ParamType;
Eli Friedman06ed2a52009-10-20 08:27:19 +00002052 if (ParamType->isMemberPointerType())
2053 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NullToMemberPointer);
2054 else
2055 ImpCastExprToType(Arg, ParamType, CastExpr::CK_BitCast);
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002056 } else if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002057 ArgType = Context.getPointerType(ArgType);
Eli Friedman06ed2a52009-10-20 08:27:19 +00002058 ImpCastExprToType(Arg, ArgType, CastExpr::CK_FunctionToPointerDecay);
Mike Stump11289f42009-09-09 15:08:12 +00002059 } else if (FunctionDecl *Fn
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002060 = ResolveAddressOfOverloadedFunction(Arg, ParamType, true)) {
Douglas Gregor171c45a2009-02-18 21:56:37 +00002061 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
2062 return true;
2063
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00002064 Arg = FixOverloadedFunctionReference(Arg, Fn);
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002065 ArgType = Arg->getType();
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002066 if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002067 ArgType = Context.getPointerType(Arg->getType());
Eli Friedman06ed2a52009-10-20 08:27:19 +00002068 ImpCastExprToType(Arg, ArgType, CastExpr::CK_FunctionToPointerDecay);
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002069 }
2070 }
2071
Mike Stump11289f42009-09-09 15:08:12 +00002072 if (!Context.hasSameUnqualifiedType(ArgType,
Douglas Gregorccb07762009-02-11 19:52:55 +00002073 ParamType.getNonReferenceType())) {
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002074 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002075 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002076 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002077 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002078 Diag(Param->getLocation(), diag::note_template_param_here);
2079 return true;
2080 }
Mike Stump11289f42009-09-09 15:08:12 +00002081
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002082 if (ParamType->isMemberPointerType()) {
2083 NamedDecl *Member = 0;
2084 if (CheckTemplateArgumentPointerToMember(Arg, Member))
2085 return true;
2086
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002087 if (Member)
2088 Member = cast<NamedDecl>(Member->getCanonicalDecl());
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002089 Converted = TemplateArgument(StartLoc, Member);
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002090 return false;
2091 }
Mike Stump11289f42009-09-09 15:08:12 +00002092
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002093 NamedDecl *Entity = 0;
2094 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2095 return true;
2096
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002097 if (Entity)
2098 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002099 Converted = TemplateArgument(StartLoc, Entity);
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002100 return false;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002101 }
2102
Chris Lattner696197c2009-02-20 21:37:53 +00002103 if (ParamType->isPointerType()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002104 // -- for a non-type template-parameter of type pointer to
2105 // object, qualification conversions (4.4) and the
2106 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl576fd422009-05-10 18:38:11 +00002107 // C++0x also allows a value of std::nullptr_t.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002108 assert(ParamType->getAs<PointerType>()->getPointeeType()->isObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002109 "Only object pointers allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00002110
Sebastian Redl576fd422009-05-10 18:38:11 +00002111 if (ArgType->isNullPtrType()) {
2112 ArgType = ParamType;
Eli Friedman06ed2a52009-10-20 08:27:19 +00002113 ImpCastExprToType(Arg, ParamType, CastExpr::CK_BitCast);
Sebastian Redl576fd422009-05-10 18:38:11 +00002114 } else if (ArgType->isArrayType()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002115 ArgType = Context.getArrayDecayedType(ArgType);
Eli Friedman06ed2a52009-10-20 08:27:19 +00002116 ImpCastExprToType(Arg, ArgType, CastExpr::CK_ArrayToPointerDecay);
Douglas Gregora9faa442009-02-11 00:44:29 +00002117 }
Sebastian Redl576fd422009-05-10 18:38:11 +00002118
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002119 if (IsQualificationConversion(ArgType, ParamType)) {
2120 ArgType = ParamType;
Eli Friedman06ed2a52009-10-20 08:27:19 +00002121 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NoOp);
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002122 }
Mike Stump11289f42009-09-09 15:08:12 +00002123
Douglas Gregor1515f762009-02-11 18:22:40 +00002124 if (!Context.hasSameUnqualifiedType(ArgType, ParamType)) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002125 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002126 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002127 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002128 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002129 Diag(Param->getLocation(), diag::note_template_param_here);
2130 return true;
2131 }
Mike Stump11289f42009-09-09 15:08:12 +00002132
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002133 NamedDecl *Entity = 0;
2134 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2135 return true;
2136
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002137 if (Entity)
2138 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002139 Converted = TemplateArgument(StartLoc, Entity);
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002140 return false;
Douglas Gregora9faa442009-02-11 00:44:29 +00002141 }
Mike Stump11289f42009-09-09 15:08:12 +00002142
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002143 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002144 // -- For a non-type template-parameter of type reference to
2145 // object, no conversions apply. The type referred to by the
2146 // reference may be more cv-qualified than the (otherwise
2147 // identical) type of the template-argument. The
2148 // template-parameter is bound directly to the
2149 // template-argument, which must be an lvalue.
Douglas Gregor64259f52009-03-24 20:32:41 +00002150 assert(ParamRefType->getPointeeType()->isObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002151 "Only object references allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00002152
Douglas Gregor1515f762009-02-11 18:22:40 +00002153 if (!Context.hasSameUnqualifiedType(ParamRefType->getPointeeType(), ArgType)) {
Mike Stump11289f42009-09-09 15:08:12 +00002154 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002155 diag::err_template_arg_no_ref_bind)
Douglas Gregor463421d2009-03-03 04:44:36 +00002156 << InstantiatedParamType << Arg->getType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002157 << Arg->getSourceRange();
2158 Diag(Param->getLocation(), diag::note_template_param_here);
2159 return true;
2160 }
2161
Mike Stump11289f42009-09-09 15:08:12 +00002162 unsigned ParamQuals
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002163 = Context.getCanonicalType(ParamType).getCVRQualifiers();
2164 unsigned ArgQuals = Context.getCanonicalType(ArgType).getCVRQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00002165
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002166 if ((ParamQuals | ArgQuals) != ParamQuals) {
2167 Diag(Arg->getSourceRange().getBegin(),
2168 diag::err_template_arg_ref_bind_ignores_quals)
Douglas Gregor463421d2009-03-03 04:44:36 +00002169 << InstantiatedParamType << Arg->getType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002170 << Arg->getSourceRange();
2171 Diag(Param->getLocation(), diag::note_template_param_here);
2172 return true;
2173 }
Mike Stump11289f42009-09-09 15:08:12 +00002174
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002175 NamedDecl *Entity = 0;
2176 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2177 return true;
2178
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002179 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002180 Converted = TemplateArgument(StartLoc, Entity);
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002181 return false;
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002182 }
Douglas Gregor0e558532009-02-11 16:16:59 +00002183
2184 // -- For a non-type template-parameter of type pointer to data
2185 // member, qualification conversions (4.4) are applied.
Sebastian Redl576fd422009-05-10 18:38:11 +00002186 // C++0x allows std::nullptr_t values.
Douglas Gregor0e558532009-02-11 16:16:59 +00002187 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
2188
Douglas Gregor1515f762009-02-11 18:22:40 +00002189 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
Douglas Gregor0e558532009-02-11 16:16:59 +00002190 // Types match exactly: nothing more to do here.
Sebastian Redl576fd422009-05-10 18:38:11 +00002191 } else if (ArgType->isNullPtrType()) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00002192 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NullToMemberPointer);
Douglas Gregor0e558532009-02-11 16:16:59 +00002193 } else if (IsQualificationConversion(ArgType, ParamType)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00002194 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NoOp);
Douglas Gregor0e558532009-02-11 16:16:59 +00002195 } else {
2196 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002197 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor0e558532009-02-11 16:16:59 +00002198 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002199 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor0e558532009-02-11 16:16:59 +00002200 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00002201 return true;
Douglas Gregor0e558532009-02-11 16:16:59 +00002202 }
2203
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002204 NamedDecl *Member = 0;
2205 if (CheckTemplateArgumentPointerToMember(Arg, Member))
2206 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002207
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002208 if (Member)
2209 Member = cast<NamedDecl>(Member->getCanonicalDecl());
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002210 Converted = TemplateArgument(StartLoc, Member);
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002211 return false;
Douglas Gregord32e0282009-02-09 23:23:08 +00002212}
2213
2214/// \brief Check a template argument against its corresponding
2215/// template template parameter.
2216///
2217/// This routine implements the semantics of C++ [temp.arg.template].
2218/// It returns true if an error occurred, and false otherwise.
2219bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
2220 DeclRefExpr *Arg) {
Douglas Gregor85e0f662009-02-10 00:24:35 +00002221 assert(isa<TemplateDecl>(Arg->getDecl()) && "Only template decls allowed");
2222 TemplateDecl *Template = cast<TemplateDecl>(Arg->getDecl());
2223
2224 // C++ [temp.arg.template]p1:
2225 // A template-argument for a template template-parameter shall be
2226 // the name of a class template, expressed as id-expression. Only
2227 // primary class templates are considered when matching the
2228 // template template argument with the corresponding parameter;
2229 // partial specializations are not considered even if their
2230 // parameter lists match that of the template template parameter.
Douglas Gregord5222052009-06-12 19:43:02 +00002231 //
2232 // Note that we also allow template template parameters here, which
2233 // will happen when we are dealing with, e.g., class template
2234 // partial specializations.
Mike Stump11289f42009-09-09 15:08:12 +00002235 if (!isa<ClassTemplateDecl>(Template) &&
Douglas Gregord5222052009-06-12 19:43:02 +00002236 !isa<TemplateTemplateParmDecl>(Template)) {
Mike Stump11289f42009-09-09 15:08:12 +00002237 assert(isa<FunctionTemplateDecl>(Template) &&
Douglas Gregor85e0f662009-02-10 00:24:35 +00002238 "Only function templates are possible here");
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002239 Diag(Arg->getLocStart(), diag::err_template_arg_not_class_template);
2240 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
Douglas Gregor85e0f662009-02-10 00:24:35 +00002241 << Template;
2242 }
2243
2244 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
2245 Param->getTemplateParameters(),
2246 true, true,
2247 Arg->getSourceRange().getBegin());
Douglas Gregord32e0282009-02-09 23:23:08 +00002248}
2249
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002250/// \brief Determine whether the given template parameter lists are
2251/// equivalent.
2252///
Mike Stump11289f42009-09-09 15:08:12 +00002253/// \param New The new template parameter list, typically written in the
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002254/// source code as part of a new template declaration.
2255///
2256/// \param Old The old template parameter list, typically found via
2257/// name lookup of the template declared with this template parameter
2258/// list.
2259///
2260/// \param Complain If true, this routine will produce a diagnostic if
2261/// the template parameter lists are not equivalent.
2262///
Douglas Gregor85e0f662009-02-10 00:24:35 +00002263/// \param IsTemplateTemplateParm If true, this routine is being
2264/// called to compare the template parameter lists of a template
2265/// template parameter.
2266///
2267/// \param TemplateArgLoc If this source location is valid, then we
2268/// are actually checking the template parameter list of a template
2269/// argument (New) against the template parameter list of its
2270/// corresponding template template parameter (Old). We produce
2271/// slightly different diagnostics in this scenario.
2272///
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002273/// \returns True if the template parameter lists are equal, false
2274/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002275bool
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002276Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
2277 TemplateParameterList *Old,
2278 bool Complain,
Douglas Gregor85e0f662009-02-10 00:24:35 +00002279 bool IsTemplateTemplateParm,
2280 SourceLocation TemplateArgLoc) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002281 if (Old->size() != New->size()) {
2282 if (Complain) {
Douglas Gregor85e0f662009-02-10 00:24:35 +00002283 unsigned NextDiag = diag::err_template_param_list_different_arity;
2284 if (TemplateArgLoc.isValid()) {
2285 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
2286 NextDiag = diag::note_template_param_list_different_arity;
Mike Stump11289f42009-09-09 15:08:12 +00002287 }
Douglas Gregor85e0f662009-02-10 00:24:35 +00002288 Diag(New->getTemplateLoc(), NextDiag)
2289 << (New->size() > Old->size())
2290 << IsTemplateTemplateParm
2291 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002292 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
2293 << IsTemplateTemplateParm
2294 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
2295 }
2296
2297 return false;
2298 }
2299
2300 for (TemplateParameterList::iterator OldParm = Old->begin(),
2301 OldParmEnd = Old->end(), NewParm = New->begin();
2302 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
2303 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
Douglas Gregor23061de2009-06-24 16:50:40 +00002304 if (Complain) {
2305 unsigned NextDiag = diag::err_template_param_different_kind;
2306 if (TemplateArgLoc.isValid()) {
2307 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
2308 NextDiag = diag::note_template_param_different_kind;
2309 }
2310 Diag((*NewParm)->getLocation(), NextDiag)
2311 << IsTemplateTemplateParm;
2312 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
2313 << IsTemplateTemplateParm;
Douglas Gregor85e0f662009-02-10 00:24:35 +00002314 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002315 return false;
2316 }
2317
2318 if (isa<TemplateTypeParmDecl>(*OldParm)) {
2319 // Okay; all template type parameters are equivalent (since we
Douglas Gregor85e0f662009-02-10 00:24:35 +00002320 // know we're at the same index).
2321#if 0
Mike Stump87c57ac2009-05-16 07:39:55 +00002322 // FIXME: Enable this code in debug mode *after* we properly go through
2323 // and "instantiate" the template parameter lists of template template
2324 // parameters. It's only after this instantiation that (1) any dependent
2325 // types within the template parameter list of the template template
2326 // parameter can be checked, and (2) the template type parameter depths
Douglas Gregor85e0f662009-02-10 00:24:35 +00002327 // will match up.
Mike Stump11289f42009-09-09 15:08:12 +00002328 QualType OldParmType
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002329 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*OldParm));
Mike Stump11289f42009-09-09 15:08:12 +00002330 QualType NewParmType
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002331 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*NewParm));
Mike Stump11289f42009-09-09 15:08:12 +00002332 assert(Context.getCanonicalType(OldParmType) ==
2333 Context.getCanonicalType(NewParmType) &&
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002334 "type parameter mismatch?");
2335#endif
Mike Stump11289f42009-09-09 15:08:12 +00002336 } else if (NonTypeTemplateParmDecl *OldNTTP
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002337 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
2338 // The types of non-type template parameters must agree.
2339 NonTypeTemplateParmDecl *NewNTTP
2340 = cast<NonTypeTemplateParmDecl>(*NewParm);
2341 if (Context.getCanonicalType(OldNTTP->getType()) !=
2342 Context.getCanonicalType(NewNTTP->getType())) {
2343 if (Complain) {
Douglas Gregor85e0f662009-02-10 00:24:35 +00002344 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
2345 if (TemplateArgLoc.isValid()) {
Mike Stump11289f42009-09-09 15:08:12 +00002346 Diag(TemplateArgLoc,
Douglas Gregor85e0f662009-02-10 00:24:35 +00002347 diag::err_template_arg_template_params_mismatch);
2348 NextDiag = diag::note_template_nontype_parm_different_type;
2349 }
2350 Diag(NewNTTP->getLocation(), NextDiag)
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002351 << NewNTTP->getType()
2352 << IsTemplateTemplateParm;
Mike Stump11289f42009-09-09 15:08:12 +00002353 Diag(OldNTTP->getLocation(),
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002354 diag::note_template_nontype_parm_prev_declaration)
2355 << OldNTTP->getType();
2356 }
2357 return false;
2358 }
2359 } else {
2360 // The template parameter lists of template template
2361 // parameters must agree.
2362 // FIXME: Could we perform a faster "type" comparison here?
Mike Stump11289f42009-09-09 15:08:12 +00002363 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002364 "Only template template parameters handled here");
Mike Stump11289f42009-09-09 15:08:12 +00002365 TemplateTemplateParmDecl *OldTTP
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002366 = cast<TemplateTemplateParmDecl>(*OldParm);
2367 TemplateTemplateParmDecl *NewTTP
2368 = cast<TemplateTemplateParmDecl>(*NewParm);
2369 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
2370 OldTTP->getTemplateParameters(),
2371 Complain,
Douglas Gregor85e0f662009-02-10 00:24:35 +00002372 /*IsTemplateTemplateParm=*/true,
2373 TemplateArgLoc))
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002374 return false;
2375 }
2376 }
2377
2378 return true;
2379}
2380
2381/// \brief Check whether a template can be declared within this scope.
2382///
2383/// If the template declaration is valid in this scope, returns
2384/// false. Otherwise, issues a diagnostic and returns true.
Mike Stump11289f42009-09-09 15:08:12 +00002385bool
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002386Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002387 // Find the nearest enclosing declaration scope.
2388 while ((S->getFlags() & Scope::DeclScope) == 0 ||
2389 (S->getFlags() & Scope::TemplateParamScope) != 0)
2390 S = S->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00002391
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002392 // C++ [temp]p2:
2393 // A template-declaration can appear only as a namespace scope or
2394 // class scope declaration.
2395 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
Eli Friedmandfbd0c42009-07-31 01:43:05 +00002396 if (Ctx && isa<LinkageSpecDecl>(Ctx) &&
2397 cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
Mike Stump11289f42009-09-09 15:08:12 +00002398 return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002399 << TemplateParams->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002400
Eli Friedmandfbd0c42009-07-31 01:43:05 +00002401 while (Ctx && isa<LinkageSpecDecl>(Ctx))
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002402 Ctx = Ctx->getParent();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002403
2404 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
2405 return false;
2406
Mike Stump11289f42009-09-09 15:08:12 +00002407 return Diag(TemplateParams->getTemplateLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002408 diag::err_template_outside_namespace_or_class_scope)
2409 << TemplateParams->getSourceRange();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002410}
Douglas Gregor67a65642009-02-17 23:15:12 +00002411
Douglas Gregor54888652009-10-07 00:13:32 +00002412/// \brief Determine what kind of template specialization the given declaration
2413/// is.
2414static TemplateSpecializationKind getTemplateSpecializationKind(NamedDecl *D) {
2415 if (!D)
2416 return TSK_Undeclared;
2417
Douglas Gregorbbe8f462009-10-08 15:14:33 +00002418 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
2419 return Record->getTemplateSpecializationKind();
Douglas Gregor54888652009-10-07 00:13:32 +00002420 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
2421 return Function->getTemplateSpecializationKind();
Douglas Gregor86d142a2009-10-08 07:24:58 +00002422 if (VarDecl *Var = dyn_cast<VarDecl>(D))
2423 return Var->getTemplateSpecializationKind();
2424
Douglas Gregor54888652009-10-07 00:13:32 +00002425 return TSK_Undeclared;
2426}
2427
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00002428/// \brief Check whether a specialization is well-formed in the current
2429/// context.
Douglas Gregorf47b9112009-02-25 22:02:03 +00002430///
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00002431/// This routine determines whether a template specialization can be declared
2432/// in the current context (C++ [temp.expl.spec]p2).
Douglas Gregor54888652009-10-07 00:13:32 +00002433///
2434/// \param S the semantic analysis object for which this check is being
2435/// performed.
2436///
2437/// \param Specialized the entity being specialized or instantiated, which
2438/// may be a kind of template (class template, function template, etc.) or
2439/// a member of a class template (member function, static data member,
2440/// member class).
2441///
2442/// \param PrevDecl the previous declaration of this entity, if any.
2443///
2444/// \param Loc the location of the explicit specialization or instantiation of
2445/// this entity.
2446///
2447/// \param IsPartialSpecialization whether this is a partial specialization of
2448/// a class template.
2449///
Douglas Gregor54888652009-10-07 00:13:32 +00002450/// \returns true if there was an error that we cannot recover from, false
2451/// otherwise.
2452static bool CheckTemplateSpecializationScope(Sema &S,
2453 NamedDecl *Specialized,
2454 NamedDecl *PrevDecl,
2455 SourceLocation Loc,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00002456 bool IsPartialSpecialization) {
Douglas Gregor54888652009-10-07 00:13:32 +00002457 // Keep these "kind" numbers in sync with the %select statements in the
2458 // various diagnostics emitted by this routine.
2459 int EntityKind = 0;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00002460 bool isTemplateSpecialization = false;
2461 if (isa<ClassTemplateDecl>(Specialized)) {
Douglas Gregor54888652009-10-07 00:13:32 +00002462 EntityKind = IsPartialSpecialization? 1 : 0;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00002463 isTemplateSpecialization = true;
2464 } else if (isa<FunctionTemplateDecl>(Specialized)) {
Douglas Gregor54888652009-10-07 00:13:32 +00002465 EntityKind = 2;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00002466 isTemplateSpecialization = true;
2467 } else if (isa<CXXMethodDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00002468 EntityKind = 3;
2469 else if (isa<VarDecl>(Specialized))
2470 EntityKind = 4;
2471 else if (isa<RecordDecl>(Specialized))
2472 EntityKind = 5;
2473 else {
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00002474 S.Diag(Loc, diag::err_template_spec_unknown_kind);
2475 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregor54888652009-10-07 00:13:32 +00002476 return true;
2477 }
2478
Douglas Gregorf47b9112009-02-25 22:02:03 +00002479 // C++ [temp.expl.spec]p2:
2480 // An explicit specialization shall be declared in the namespace
2481 // of which the template is a member, or, for member templates, in
2482 // the namespace of which the enclosing class or enclosing class
2483 // template is a member. An explicit specialization of a member
2484 // function, member class or static data member of a class
2485 // template shall be declared in the namespace of which the class
2486 // template is a member. Such a declaration may also be a
2487 // definition. If the declaration is not a definition, the
2488 // specialization may be defined later in the name- space in which
2489 // the explicit specialization was declared, or in a namespace
2490 // that encloses the one in which the explicit specialization was
2491 // declared.
Douglas Gregor54888652009-10-07 00:13:32 +00002492 if (S.CurContext->getLookupContext()->isFunctionOrMethod()) {
2493 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00002494 << Specialized;
Douglas Gregorf47b9112009-02-25 22:02:03 +00002495 return true;
2496 }
Douglas Gregore4b05162009-10-07 17:21:34 +00002497
Douglas Gregor40fb7442009-10-07 17:30:37 +00002498 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
2499 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00002500 << Specialized;
Douglas Gregor40fb7442009-10-07 17:30:37 +00002501 return true;
2502 }
2503
Douglas Gregore4b05162009-10-07 17:21:34 +00002504 // C++ [temp.class.spec]p6:
2505 // A class template partial specialization may be declared or redeclared
2506 // in any namespace scope in which its definition may be defined (14.5.1
2507 // and 14.5.2).
Douglas Gregor54888652009-10-07 00:13:32 +00002508 bool ComplainedAboutScope = false;
Douglas Gregore4b05162009-10-07 17:21:34 +00002509 DeclContext *SpecializedContext
Douglas Gregor54888652009-10-07 00:13:32 +00002510 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregore4b05162009-10-07 17:21:34 +00002511 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00002512 if ((!PrevDecl ||
2513 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
2514 getTemplateSpecializationKind(PrevDecl) == TSK_ImplicitInstantiation)){
2515 // There is no prior declaration of this entity, so this
2516 // specialization must be in the same context as the template
2517 // itself.
2518 if (!DC->Equals(SpecializedContext)) {
2519 if (isa<TranslationUnitDecl>(SpecializedContext))
2520 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global)
2521 << EntityKind << Specialized;
2522 else if (isa<NamespaceDecl>(SpecializedContext))
2523 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope)
2524 << EntityKind << Specialized
2525 << cast<NamedDecl>(SpecializedContext);
2526
2527 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
2528 ComplainedAboutScope = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00002529 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00002530 }
Douglas Gregor54888652009-10-07 00:13:32 +00002531
2532 // Make sure that this redeclaration (or definition) occurs in an enclosing
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00002533 // namespace.
Douglas Gregor54888652009-10-07 00:13:32 +00002534 // Note that HandleDeclarator() performs this check for explicit
2535 // specializations of function templates, static data members, and member
2536 // functions, so we skip the check here for those kinds of entities.
2537 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
Douglas Gregore4b05162009-10-07 17:21:34 +00002538 // Should we refactor that check, so that it occurs later?
2539 if (!ComplainedAboutScope && !DC->Encloses(SpecializedContext) &&
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00002540 !(isa<FunctionTemplateDecl>(Specialized) || isa<VarDecl>(Specialized) ||
2541 isa<FunctionDecl>(Specialized))) {
Douglas Gregor54888652009-10-07 00:13:32 +00002542 if (isa<TranslationUnitDecl>(SpecializedContext))
2543 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
2544 << EntityKind << Specialized;
2545 else if (isa<NamespaceDecl>(SpecializedContext))
2546 S.Diag(Loc, diag::err_template_spec_redecl_out_of_scope)
2547 << EntityKind << Specialized
2548 << cast<NamedDecl>(SpecializedContext);
2549
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00002550 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregorf47b9112009-02-25 22:02:03 +00002551 }
Douglas Gregor54888652009-10-07 00:13:32 +00002552
2553 // FIXME: check for specialization-after-instantiation errors and such.
2554
Douglas Gregorf47b9112009-02-25 22:02:03 +00002555 return false;
2556}
Douglas Gregor54888652009-10-07 00:13:32 +00002557
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002558/// \brief Check the non-type template arguments of a class template
2559/// partial specialization according to C++ [temp.class.spec]p9.
2560///
Douglas Gregor09a30232009-06-12 22:08:06 +00002561/// \param TemplateParams the template parameters of the primary class
2562/// template.
2563///
2564/// \param TemplateArg the template arguments of the class template
2565/// partial specialization.
2566///
2567/// \param MirrorsPrimaryTemplate will be set true if the class
2568/// template partial specialization arguments are identical to the
2569/// implicit template arguments of the primary template. This is not
2570/// necessarily an error (C++0x), and it is left to the caller to diagnose
2571/// this condition when it is an error.
2572///
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002573/// \returns true if there was an error, false otherwise.
2574bool Sema::CheckClassTemplatePartialSpecializationArgs(
2575 TemplateParameterList *TemplateParams,
Anders Carlsson40c1d492009-06-13 18:20:51 +00002576 const TemplateArgumentListBuilder &TemplateArgs,
Douglas Gregor09a30232009-06-12 22:08:06 +00002577 bool &MirrorsPrimaryTemplate) {
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002578 // FIXME: the interface to this function will have to change to
2579 // accommodate variadic templates.
Douglas Gregor09a30232009-06-12 22:08:06 +00002580 MirrorsPrimaryTemplate = true;
Mike Stump11289f42009-09-09 15:08:12 +00002581
Anders Carlsson5947ddf2009-06-23 01:26:57 +00002582 const TemplateArgument *ArgList = TemplateArgs.getFlatArguments();
Mike Stump11289f42009-09-09 15:08:12 +00002583
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002584 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
Douglas Gregor09a30232009-06-12 22:08:06 +00002585 // Determine whether the template argument list of the partial
2586 // specialization is identical to the implicit argument list of
2587 // the primary template. The caller may need to diagnostic this as
2588 // an error per C++ [temp.class.spec]p9b3.
2589 if (MirrorsPrimaryTemplate) {
Mike Stump11289f42009-09-09 15:08:12 +00002590 if (TemplateTypeParmDecl *TTP
Douglas Gregor09a30232009-06-12 22:08:06 +00002591 = dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(I))) {
2592 if (Context.getCanonicalType(Context.getTypeDeclType(TTP)) !=
Anders Carlsson40c1d492009-06-13 18:20:51 +00002593 Context.getCanonicalType(ArgList[I].getAsType()))
Douglas Gregor09a30232009-06-12 22:08:06 +00002594 MirrorsPrimaryTemplate = false;
2595 } else if (TemplateTemplateParmDecl *TTP
2596 = dyn_cast<TemplateTemplateParmDecl>(
2597 TemplateParams->getParam(I))) {
2598 // FIXME: We should settle on either Declaration storage or
2599 // Expression storage for template template parameters.
Mike Stump11289f42009-09-09 15:08:12 +00002600 TemplateTemplateParmDecl *ArgDecl
Douglas Gregor09a30232009-06-12 22:08:06 +00002601 = dyn_cast_or_null<TemplateTemplateParmDecl>(
Anders Carlsson40c1d492009-06-13 18:20:51 +00002602 ArgList[I].getAsDecl());
Douglas Gregor09a30232009-06-12 22:08:06 +00002603 if (!ArgDecl)
Mike Stump11289f42009-09-09 15:08:12 +00002604 if (DeclRefExpr *DRE
Anders Carlsson40c1d492009-06-13 18:20:51 +00002605 = dyn_cast_or_null<DeclRefExpr>(ArgList[I].getAsExpr()))
Douglas Gregor09a30232009-06-12 22:08:06 +00002606 ArgDecl = dyn_cast<TemplateTemplateParmDecl>(DRE->getDecl());
2607
2608 if (!ArgDecl ||
2609 ArgDecl->getIndex() != TTP->getIndex() ||
2610 ArgDecl->getDepth() != TTP->getDepth())
2611 MirrorsPrimaryTemplate = false;
2612 }
2613 }
2614
Mike Stump11289f42009-09-09 15:08:12 +00002615 NonTypeTemplateParmDecl *Param
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002616 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
Douglas Gregor09a30232009-06-12 22:08:06 +00002617 if (!Param) {
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002618 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00002619 }
2620
Anders Carlsson40c1d492009-06-13 18:20:51 +00002621 Expr *ArgExpr = ArgList[I].getAsExpr();
Douglas Gregor09a30232009-06-12 22:08:06 +00002622 if (!ArgExpr) {
2623 MirrorsPrimaryTemplate = false;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002624 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00002625 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002626
2627 // C++ [temp.class.spec]p8:
2628 // A non-type argument is non-specialized if it is the name of a
2629 // non-type parameter. All other non-type arguments are
2630 // specialized.
2631 //
2632 // Below, we check the two conditions that only apply to
2633 // specialized non-type arguments, so skip any non-specialized
2634 // arguments.
2635 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Mike Stump11289f42009-09-09 15:08:12 +00002636 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor09a30232009-06-12 22:08:06 +00002637 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00002638 if (MirrorsPrimaryTemplate &&
Douglas Gregor09a30232009-06-12 22:08:06 +00002639 (Param->getIndex() != NTTP->getIndex() ||
2640 Param->getDepth() != NTTP->getDepth()))
2641 MirrorsPrimaryTemplate = false;
2642
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002643 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00002644 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002645
2646 // C++ [temp.class.spec]p9:
2647 // Within the argument list of a class template partial
2648 // specialization, the following restrictions apply:
2649 // -- A partially specialized non-type argument expression
2650 // shall not involve a template parameter of the partial
2651 // specialization except when the argument expression is a
2652 // simple identifier.
2653 if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
Mike Stump11289f42009-09-09 15:08:12 +00002654 Diag(ArgExpr->getLocStart(),
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002655 diag::err_dependent_non_type_arg_in_partial_spec)
2656 << ArgExpr->getSourceRange();
2657 return true;
2658 }
2659
2660 // -- The type of a template parameter corresponding to a
2661 // specialized non-type argument shall not be dependent on a
2662 // parameter of the specialization.
2663 if (Param->getType()->isDependentType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002664 Diag(ArgExpr->getLocStart(),
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002665 diag::err_dependent_typed_non_type_arg_in_partial_spec)
2666 << Param->getType()
2667 << ArgExpr->getSourceRange();
2668 Diag(Param->getLocation(), diag::note_template_param_here);
2669 return true;
2670 }
Douglas Gregor09a30232009-06-12 22:08:06 +00002671
2672 MirrorsPrimaryTemplate = false;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002673 }
2674
2675 return false;
2676}
2677
Douglas Gregorc08f4892009-03-25 00:13:59 +00002678Sema::DeclResult
John McCall9bb74a52009-07-31 02:45:11 +00002679Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
2680 TagUseKind TUK,
Mike Stump11289f42009-09-09 15:08:12 +00002681 SourceLocation KWLoc,
Douglas Gregor67a65642009-02-17 23:15:12 +00002682 const CXXScopeSpec &SS,
Douglas Gregordc572a32009-03-30 22:58:21 +00002683 TemplateTy TemplateD,
Douglas Gregor67a65642009-02-17 23:15:12 +00002684 SourceLocation TemplateNameLoc,
2685 SourceLocation LAngleLoc,
Douglas Gregorc40290e2009-03-09 23:48:35 +00002686 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregor67a65642009-02-17 23:15:12 +00002687 SourceLocation *TemplateArgLocs,
2688 SourceLocation RAngleLoc,
2689 AttributeList *Attr,
2690 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregor2208a292009-09-26 20:57:03 +00002691 assert(TUK != TUK_Reference && "References are not specializations");
John McCall06f6fe8d2009-09-04 01:14:41 +00002692
Douglas Gregor67a65642009-02-17 23:15:12 +00002693 // Find the class template we're specializing
Douglas Gregordc572a32009-03-30 22:58:21 +00002694 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump11289f42009-09-09 15:08:12 +00002695 ClassTemplateDecl *ClassTemplate
Douglas Gregordc572a32009-03-30 22:58:21 +00002696 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
Douglas Gregor67a65642009-02-17 23:15:12 +00002697
Douglas Gregor5c0405d2009-10-07 22:35:40 +00002698 bool isExplicitSpecialization = false;
Douglas Gregor2373c592009-05-31 09:31:02 +00002699 bool isPartialSpecialization = false;
2700
Douglas Gregorf47b9112009-02-25 22:02:03 +00002701 // Check the validity of the template headers that introduce this
2702 // template.
Douglas Gregor2208a292009-09-26 20:57:03 +00002703 // FIXME: We probably shouldn't complain about these headers for
2704 // friend declarations.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002705 TemplateParameterList *TemplateParams
Mike Stump11289f42009-09-09 15:08:12 +00002706 = MatchTemplateParametersToScopeSpecifier(TemplateNameLoc, SS,
2707 (TemplateParameterList**)TemplateParameterLists.get(),
Douglas Gregor5c0405d2009-10-07 22:35:40 +00002708 TemplateParameterLists.size(),
2709 isExplicitSpecialization);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002710 if (TemplateParams && TemplateParams->size() > 0) {
2711 isPartialSpecialization = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00002712
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002713 // C++ [temp.class.spec]p10:
2714 // The template parameter list of a specialization shall not
2715 // contain default template argument values.
2716 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
2717 Decl *Param = TemplateParams->getParam(I);
2718 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
2719 if (TTP->hasDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00002720 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002721 diag::err_default_arg_in_partial_spec);
2722 TTP->setDefaultArgument(QualType(), SourceLocation(), false);
2723 }
2724 } else if (NonTypeTemplateParmDecl *NTTP
2725 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2726 if (Expr *DefArg = NTTP->getDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00002727 Diag(NTTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002728 diag::err_default_arg_in_partial_spec)
2729 << DefArg->getSourceRange();
2730 NTTP->setDefaultArgument(0);
2731 DefArg->Destroy(Context);
2732 }
2733 } else {
2734 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
2735 if (Expr *DefArg = TTP->getDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00002736 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002737 diag::err_default_arg_in_partial_spec)
2738 << DefArg->getSourceRange();
2739 TTP->setDefaultArgument(0);
2740 DefArg->Destroy(Context);
Douglas Gregord5222052009-06-12 19:43:02 +00002741 }
2742 }
2743 }
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00002744 } else if (TemplateParams) {
2745 if (TUK == TUK_Friend)
2746 Diag(KWLoc, diag::err_template_spec_friend)
2747 << CodeModificationHint::CreateRemoval(
2748 SourceRange(TemplateParams->getTemplateLoc(),
2749 TemplateParams->getRAngleLoc()))
2750 << SourceRange(LAngleLoc, RAngleLoc);
2751 else
2752 isExplicitSpecialization = true;
2753 } else if (TUK != TUK_Friend) {
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002754 Diag(KWLoc, diag::err_template_spec_needs_header)
2755 << CodeModificationHint::CreateInsertion(KWLoc, "template<> ");
Douglas Gregor5c0405d2009-10-07 22:35:40 +00002756 isExplicitSpecialization = true;
2757 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00002758
Douglas Gregor67a65642009-02-17 23:15:12 +00002759 // Check that the specialization uses the same tag kind as the
2760 // original template.
2761 TagDecl::TagKind Kind;
2762 switch (TagSpec) {
2763 default: assert(0 && "Unknown tag type!");
2764 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2765 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2766 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2767 }
Douglas Gregord9034f02009-05-14 16:41:31 +00002768 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump11289f42009-09-09 15:08:12 +00002769 Kind, KWLoc,
Douglas Gregord9034f02009-05-14 16:41:31 +00002770 *ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00002771 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00002772 << ClassTemplate
Mike Stump11289f42009-09-09 15:08:12 +00002773 << CodeModificationHint::CreateReplacement(KWLoc,
Douglas Gregor170512f2009-04-01 23:51:29 +00002774 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00002775 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregor67a65642009-02-17 23:15:12 +00002776 diag::note_previous_use);
2777 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
2778 }
2779
Douglas Gregorc40290e2009-03-09 23:48:35 +00002780 // Translate the parser's template argument list in our AST format.
2781 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
2782 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
2783
Douglas Gregor67a65642009-02-17 23:15:12 +00002784 // Check that the template argument list is well-formed for this
2785 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00002786 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
2787 TemplateArgs.size());
Mike Stump11289f42009-09-09 15:08:12 +00002788 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
Anders Carlsson40c1d492009-06-13 18:20:51 +00002789 TemplateArgs.data(), TemplateArgs.size(),
Douglas Gregore3f1f352009-07-01 00:28:38 +00002790 RAngleLoc, false, Converted))
Douglas Gregorc08f4892009-03-25 00:13:59 +00002791 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00002792
Mike Stump11289f42009-09-09 15:08:12 +00002793 assert((Converted.structuredSize() ==
Douglas Gregor67a65642009-02-17 23:15:12 +00002794 ClassTemplate->getTemplateParameters()->size()) &&
2795 "Converted template argument list is too short!");
Mike Stump11289f42009-09-09 15:08:12 +00002796
Douglas Gregor2373c592009-05-31 09:31:02 +00002797 // Find the class template (partial) specialization declaration that
Douglas Gregor67a65642009-02-17 23:15:12 +00002798 // corresponds to these arguments.
2799 llvm::FoldingSetNodeID ID;
Douglas Gregord5222052009-06-12 19:43:02 +00002800 if (isPartialSpecialization) {
Douglas Gregor09a30232009-06-12 22:08:06 +00002801 bool MirrorsPrimaryTemplate;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002802 if (CheckClassTemplatePartialSpecializationArgs(
2803 ClassTemplate->getTemplateParameters(),
Anders Carlsson5947ddf2009-06-23 01:26:57 +00002804 Converted, MirrorsPrimaryTemplate))
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002805 return true;
2806
Douglas Gregor09a30232009-06-12 22:08:06 +00002807 if (MirrorsPrimaryTemplate) {
2808 // C++ [temp.class.spec]p9b3:
2809 //
Mike Stump11289f42009-09-09 15:08:12 +00002810 // -- The argument list of the specialization shall not be identical
2811 // to the implicit argument list of the primary template.
Douglas Gregor09a30232009-06-12 22:08:06 +00002812 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
John McCall9bb74a52009-07-31 02:45:11 +00002813 << (TUK == TUK_Definition)
Mike Stump11289f42009-09-09 15:08:12 +00002814 << CodeModificationHint::CreateRemoval(SourceRange(LAngleLoc,
Douglas Gregor09a30232009-06-12 22:08:06 +00002815 RAngleLoc));
John McCall9bb74a52009-07-31 02:45:11 +00002816 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
Douglas Gregor09a30232009-06-12 22:08:06 +00002817 ClassTemplate->getIdentifier(),
2818 TemplateNameLoc,
2819 Attr,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002820 TemplateParams,
Douglas Gregor09a30232009-06-12 22:08:06 +00002821 AS_none);
2822 }
2823
Douglas Gregor2208a292009-09-26 20:57:03 +00002824 // FIXME: Diagnose friend partial specializations
2825
Douglas Gregor2373c592009-05-31 09:31:02 +00002826 // FIXME: Template parameter list matters, too
Mike Stump11289f42009-09-09 15:08:12 +00002827 ClassTemplatePartialSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00002828 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00002829 Converted.flatSize(),
2830 Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00002831 } else
Anders Carlsson8aa89d42009-06-05 03:43:12 +00002832 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00002833 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00002834 Converted.flatSize(),
2835 Context);
Douglas Gregor67a65642009-02-17 23:15:12 +00002836 void *InsertPos = 0;
Douglas Gregor2373c592009-05-31 09:31:02 +00002837 ClassTemplateSpecializationDecl *PrevDecl = 0;
2838
2839 if (isPartialSpecialization)
2840 PrevDecl
Mike Stump11289f42009-09-09 15:08:12 +00002841 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
Douglas Gregor2373c592009-05-31 09:31:02 +00002842 InsertPos);
2843 else
2844 PrevDecl
2845 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor67a65642009-02-17 23:15:12 +00002846
2847 ClassTemplateSpecializationDecl *Specialization = 0;
2848
Douglas Gregorf47b9112009-02-25 22:02:03 +00002849 // Check whether we can declare a class template specialization in
2850 // the current scope.
Douglas Gregor2208a292009-09-26 20:57:03 +00002851 if (TUK != TUK_Friend &&
Douglas Gregor54888652009-10-07 00:13:32 +00002852 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00002853 TemplateNameLoc,
2854 isPartialSpecialization))
Douglas Gregorc08f4892009-03-25 00:13:59 +00002855 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00002856
Douglas Gregor15301382009-07-30 17:40:51 +00002857 // The canonical type
2858 QualType CanonType;
Douglas Gregor2208a292009-09-26 20:57:03 +00002859 if (PrevDecl &&
2860 (PrevDecl->getSpecializationKind() == TSK_Undeclared ||
2861 TUK == TUK_Friend)) {
Douglas Gregor67a65642009-02-17 23:15:12 +00002862 // Since the only prior class template specialization with these
Douglas Gregor2208a292009-09-26 20:57:03 +00002863 // arguments was referenced but not declared, or we're only
2864 // referencing this specialization as a friend, reuse that
Douglas Gregor67a65642009-02-17 23:15:12 +00002865 // declaration node as our own, updating its source location to
2866 // reflect our new declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00002867 Specialization = PrevDecl;
Douglas Gregor1e249f82009-02-25 22:18:32 +00002868 Specialization->setLocation(TemplateNameLoc);
Douglas Gregor67a65642009-02-17 23:15:12 +00002869 PrevDecl = 0;
Douglas Gregor15301382009-07-30 17:40:51 +00002870 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregor2373c592009-05-31 09:31:02 +00002871 } else if (isPartialSpecialization) {
Douglas Gregor15301382009-07-30 17:40:51 +00002872 // Build the canonical type that describes the converted template
2873 // arguments of the class template partial specialization.
2874 CanonType = Context.getTemplateSpecializationType(
2875 TemplateName(ClassTemplate),
2876 Converted.getFlatArguments(),
2877 Converted.flatSize());
2878
Douglas Gregor2373c592009-05-31 09:31:02 +00002879 // Create a new class template partial specialization declaration node.
Mike Stump11289f42009-09-09 15:08:12 +00002880 TemplateParameterList *TemplateParams
Douglas Gregor2373c592009-05-31 09:31:02 +00002881 = static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
2882 ClassTemplatePartialSpecializationDecl *PrevPartial
2883 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
Mike Stump11289f42009-09-09 15:08:12 +00002884 ClassTemplatePartialSpecializationDecl *Partial
2885 = ClassTemplatePartialSpecializationDecl::Create(Context,
Douglas Gregor2373c592009-05-31 09:31:02 +00002886 ClassTemplate->getDeclContext(),
Anders Carlsson1b28c3e2009-06-05 04:06:48 +00002887 TemplateNameLoc,
2888 TemplateParams,
2889 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00002890 Converted,
Anders Carlsson1b28c3e2009-06-05 04:06:48 +00002891 PrevPartial);
Douglas Gregor2373c592009-05-31 09:31:02 +00002892
2893 if (PrevPartial) {
2894 ClassTemplate->getPartialSpecializations().RemoveNode(PrevPartial);
2895 ClassTemplate->getPartialSpecializations().GetOrInsertNode(Partial);
2896 } else {
2897 ClassTemplate->getPartialSpecializations().InsertNode(Partial, InsertPos);
2898 }
2899 Specialization = Partial;
Douglas Gregor91772d12009-06-13 00:26:55 +00002900
2901 // Check that all of the template parameters of the class template
2902 // partial specialization are deducible from the template
2903 // arguments. If not, this class template partial specialization
2904 // will never be used.
2905 llvm::SmallVector<bool, 8> DeducibleParams;
2906 DeducibleParams.resize(TemplateParams->size());
Douglas Gregore1d2ef32009-09-14 21:25:05 +00002907 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
2908 DeducibleParams);
Douglas Gregor91772d12009-06-13 00:26:55 +00002909 unsigned NumNonDeducible = 0;
2910 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I)
2911 if (!DeducibleParams[I])
2912 ++NumNonDeducible;
2913
2914 if (NumNonDeducible) {
2915 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
2916 << (NumNonDeducible > 1)
2917 << SourceRange(TemplateNameLoc, RAngleLoc);
2918 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
2919 if (!DeducibleParams[I]) {
2920 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
2921 if (Param->getDeclName())
Mike Stump11289f42009-09-09 15:08:12 +00002922 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00002923 diag::note_partial_spec_unused_parameter)
2924 << Param->getDeclName();
2925 else
Mike Stump11289f42009-09-09 15:08:12 +00002926 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00002927 diag::note_partial_spec_unused_parameter)
2928 << std::string("<anonymous>");
2929 }
2930 }
2931 }
Douglas Gregor67a65642009-02-17 23:15:12 +00002932 } else {
2933 // Create a new class template specialization declaration node for
Douglas Gregor2208a292009-09-26 20:57:03 +00002934 // this explicit specialization or friend declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00002935 Specialization
Mike Stump11289f42009-09-09 15:08:12 +00002936 = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregor67a65642009-02-17 23:15:12 +00002937 ClassTemplate->getDeclContext(),
2938 TemplateNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +00002939 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00002940 Converted,
Douglas Gregor67a65642009-02-17 23:15:12 +00002941 PrevDecl);
2942
2943 if (PrevDecl) {
2944 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
2945 ClassTemplate->getSpecializations().GetOrInsertNode(Specialization);
2946 } else {
Mike Stump11289f42009-09-09 15:08:12 +00002947 ClassTemplate->getSpecializations().InsertNode(Specialization,
Douglas Gregor67a65642009-02-17 23:15:12 +00002948 InsertPos);
2949 }
Douglas Gregor15301382009-07-30 17:40:51 +00002950
2951 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00002952 }
2953
Douglas Gregor06db9f52009-10-12 20:18:28 +00002954 // C++ [temp.expl.spec]p6:
2955 // If a template, a member template or the member of a class template is
2956 // explicitly specialized then that specialization shall be declared
2957 // before the first use of that specialization that would cause an implicit
2958 // instantiation to take place, in every translation unit in which such a
2959 // use occurs; no diagnostic is required.
2960 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
2961 SourceRange Range(TemplateNameLoc, RAngleLoc);
2962 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
2963 << Context.getTypeDeclType(Specialization) << Range;
2964
2965 Diag(PrevDecl->getPointOfInstantiation(),
2966 diag::note_instantiation_required_here)
2967 << (PrevDecl->getTemplateSpecializationKind()
2968 != TSK_ImplicitInstantiation);
2969 return true;
2970 }
2971
Douglas Gregor2208a292009-09-26 20:57:03 +00002972 // If this is not a friend, note that this is an explicit specialization.
2973 if (TUK != TUK_Friend)
2974 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00002975
2976 // Check that this isn't a redefinition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00002977 if (TUK == TUK_Definition) {
Douglas Gregor67a65642009-02-17 23:15:12 +00002978 if (RecordDecl *Def = Specialization->getDefinition(Context)) {
Douglas Gregor67a65642009-02-17 23:15:12 +00002979 SourceRange Range(TemplateNameLoc, RAngleLoc);
Mike Stump11289f42009-09-09 15:08:12 +00002980 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregor2373c592009-05-31 09:31:02 +00002981 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregor67a65642009-02-17 23:15:12 +00002982 Diag(Def->getLocation(), diag::note_previous_definition);
2983 Specialization->setInvalidDecl();
Douglas Gregorc08f4892009-03-25 00:13:59 +00002984 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00002985 }
2986 }
2987
Douglas Gregord56a91e2009-02-26 22:19:44 +00002988 // Build the fully-sugared type for this class template
2989 // specialization as the user wrote in the specialization
2990 // itself. This means that we'll pretty-print the type retrieved
2991 // from the specialization's declaration the way that the user
2992 // actually wrote the specialization, rather than formatting the
2993 // name based on the "canonical" representation used to store the
2994 // template arguments in the specialization.
Mike Stump11289f42009-09-09 15:08:12 +00002995 QualType WrittenTy
2996 = Context.getTemplateSpecializationType(Name,
Anders Carlsson40c1d492009-06-13 18:20:51 +00002997 TemplateArgs.data(),
Douglas Gregordc572a32009-03-30 22:58:21 +00002998 TemplateArgs.size(),
Douglas Gregor15301382009-07-30 17:40:51 +00002999 CanonType);
Douglas Gregor2208a292009-09-26 20:57:03 +00003000 if (TUK != TUK_Friend)
3001 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregorc40290e2009-03-09 23:48:35 +00003002 TemplateArgsIn.release();
Douglas Gregor67a65642009-02-17 23:15:12 +00003003
Douglas Gregor1e249f82009-02-25 22:18:32 +00003004 // C++ [temp.expl.spec]p9:
3005 // A template explicit specialization is in the scope of the
3006 // namespace in which the template was defined.
3007 //
3008 // We actually implement this paragraph where we set the semantic
3009 // context (in the creation of the ClassTemplateSpecializationDecl),
3010 // but we also maintain the lexical context where the actual
3011 // definition occurs.
Douglas Gregor67a65642009-02-17 23:15:12 +00003012 Specialization->setLexicalDeclContext(CurContext);
Mike Stump11289f42009-09-09 15:08:12 +00003013
Douglas Gregor67a65642009-02-17 23:15:12 +00003014 // We may be starting the definition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00003015 if (TUK == TUK_Definition)
Douglas Gregor67a65642009-02-17 23:15:12 +00003016 Specialization->startDefinition();
3017
Douglas Gregor2208a292009-09-26 20:57:03 +00003018 if (TUK == TUK_Friend) {
3019 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
3020 TemplateNameLoc,
3021 WrittenTy.getTypePtr(),
3022 /*FIXME:*/KWLoc);
3023 Friend->setAccess(AS_public);
3024 CurContext->addDecl(Friend);
3025 } else {
3026 // Add the specialization into its lexical context, so that it can
3027 // be seen when iterating through the list of declarations in that
3028 // context. However, specializations are not found by name lookup.
3029 CurContext->addDecl(Specialization);
3030 }
Chris Lattner83f095c2009-03-28 19:18:32 +00003031 return DeclPtrTy::make(Specialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00003032}
Douglas Gregor333489b2009-03-27 23:10:48 +00003033
Mike Stump11289f42009-09-09 15:08:12 +00003034Sema::DeclPtrTy
3035Sema::ActOnTemplateDeclarator(Scope *S,
Douglas Gregorb52fabb2009-06-23 23:11:28 +00003036 MultiTemplateParamsArg TemplateParameterLists,
3037 Declarator &D) {
3038 return HandleDeclarator(S, D, move(TemplateParameterLists), false);
3039}
3040
Mike Stump11289f42009-09-09 15:08:12 +00003041Sema::DeclPtrTy
3042Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
Douglas Gregor17a7c122009-06-24 00:54:41 +00003043 MultiTemplateParamsArg TemplateParameterLists,
3044 Declarator &D) {
3045 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
3046 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
3047 "Not a function declarator!");
3048 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Mike Stump11289f42009-09-09 15:08:12 +00003049
Douglas Gregor17a7c122009-06-24 00:54:41 +00003050 if (FTI.hasPrototype) {
Mike Stump11289f42009-09-09 15:08:12 +00003051 // FIXME: Diagnose arguments without names in C.
Douglas Gregor17a7c122009-06-24 00:54:41 +00003052 }
Mike Stump11289f42009-09-09 15:08:12 +00003053
Douglas Gregor17a7c122009-06-24 00:54:41 +00003054 Scope *ParentScope = FnBodyScope->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00003055
3056 DeclPtrTy DP = HandleDeclarator(ParentScope, D,
Douglas Gregor17a7c122009-06-24 00:54:41 +00003057 move(TemplateParameterLists),
3058 /*IsFunctionDefinition=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00003059 if (FunctionTemplateDecl *FunctionTemplate
Douglas Gregord8d297c2009-07-21 23:53:31 +00003060 = dyn_cast_or_null<FunctionTemplateDecl>(DP.getAs<Decl>()))
Mike Stump11289f42009-09-09 15:08:12 +00003061 return ActOnStartOfFunctionDef(FnBodyScope,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003062 DeclPtrTy::make(FunctionTemplate->getTemplatedDecl()));
Douglas Gregord8d297c2009-07-21 23:53:31 +00003063 if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(DP.getAs<Decl>()))
3064 return ActOnStartOfFunctionDef(FnBodyScope, DeclPtrTy::make(Function));
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003065 return DeclPtrTy();
Douglas Gregor17a7c122009-06-24 00:54:41 +00003066}
3067
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003068/// \brief Diagnose cases where we have an explicit template specialization
3069/// before/after an explicit template instantiation, producing diagnostics
3070/// for those cases where they are required and determining whether the
3071/// new specialization/instantiation will have any effect.
3072///
3073/// \param S the semantic analysis object.
3074///
3075/// \param NewLoc the location of the new explicit specialization or
3076/// instantiation.
3077///
3078/// \param NewTSK the kind of the new explicit specialization or instantiation.
3079///
3080/// \param PrevDecl the previous declaration of the entity.
3081///
3082/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
3083///
3084/// \param PrevPointOfInstantiation if valid, indicates where the previus
3085/// declaration was instantiated (either implicitly or explicitly).
3086///
3087/// \param SuppressNew will be set to true to indicate that the new
3088/// specialization or instantiation has no effect and should be ignored.
3089///
3090/// \returns true if there was an error that should prevent the introduction of
3091/// the new declaration into the AST, false otherwise.
3092static bool
3093CheckSpecializationInstantiationRedecl(Sema &S,
3094 SourceLocation NewLoc,
3095 TemplateSpecializationKind NewTSK,
3096 NamedDecl *PrevDecl,
3097 TemplateSpecializationKind PrevTSK,
3098 SourceLocation PrevPointOfInstantiation,
3099 bool &SuppressNew) {
3100 SuppressNew = false;
3101
3102 switch (NewTSK) {
3103 case TSK_Undeclared:
3104 case TSK_ImplicitInstantiation:
3105 assert(false && "Don't check implicit instantiations here");
3106 return false;
3107
3108 case TSK_ExplicitSpecialization:
3109 switch (PrevTSK) {
3110 case TSK_Undeclared:
3111 case TSK_ExplicitSpecialization:
3112 // Okay, we're just specializing something that is either already
3113 // explicitly specialized or has merely been mentioned without any
3114 // instantiation.
3115 return false;
3116
3117 case TSK_ImplicitInstantiation:
3118 if (PrevPointOfInstantiation.isInvalid()) {
3119 // The declaration itself has not actually been instantiated, so it is
3120 // still okay to specialize it.
3121 return false;
3122 }
3123 // Fall through
3124
3125 case TSK_ExplicitInstantiationDeclaration:
3126 case TSK_ExplicitInstantiationDefinition:
3127 assert((PrevTSK == TSK_ImplicitInstantiation ||
3128 PrevPointOfInstantiation.isValid()) &&
3129 "Explicit instantiation without point of instantiation?");
3130
3131 // C++ [temp.expl.spec]p6:
3132 // If a template, a member template or the member of a class template
3133 // is explicitly specialized then that specialization shall be declared
3134 // before the first use of that specialization that would cause an
3135 // implicit instantiation to take place, in every translation unit in
3136 // which such a use occurs; no diagnostic is required.
3137 S.Diag(NewLoc, diag::err_specialization_after_instantiation)
3138 << PrevDecl;
3139 S.Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
3140 << (PrevTSK != TSK_ImplicitInstantiation);
3141
3142 return true;
3143 }
3144 break;
3145
3146 case TSK_ExplicitInstantiationDeclaration:
3147 switch (PrevTSK) {
3148 case TSK_ExplicitInstantiationDeclaration:
3149 // This explicit instantiation declaration is redundant (that's okay).
3150 SuppressNew = true;
3151 return false;
3152
3153 case TSK_Undeclared:
3154 case TSK_ImplicitInstantiation:
3155 // We're explicitly instantiating something that may have already been
3156 // implicitly instantiated; that's fine.
3157 return false;
3158
3159 case TSK_ExplicitSpecialization:
3160 // C++0x [temp.explicit]p4:
3161 // For a given set of template parameters, if an explicit instantiation
3162 // of a template appears after a declaration of an explicit
3163 // specialization for that template, the explicit instantiation has no
3164 // effect.
3165 return false;
3166
3167 case TSK_ExplicitInstantiationDefinition:
3168 // C++0x [temp.explicit]p10:
3169 // If an entity is the subject of both an explicit instantiation
3170 // declaration and an explicit instantiation definition in the same
3171 // translation unit, the definition shall follow the declaration.
3172 S.Diag(NewLoc,
3173 diag::err_explicit_instantiation_declaration_after_definition);
3174 S.Diag(PrevPointOfInstantiation,
3175 diag::note_explicit_instantiation_definition_here);
3176 assert(PrevPointOfInstantiation.isValid() &&
3177 "Explicit instantiation without point of instantiation?");
3178 SuppressNew = true;
3179 return false;
3180 }
3181 break;
3182
3183 case TSK_ExplicitInstantiationDefinition:
3184 switch (PrevTSK) {
3185 case TSK_Undeclared:
3186 case TSK_ImplicitInstantiation:
3187 // We're explicitly instantiating something that may have already been
3188 // implicitly instantiated; that's fine.
3189 return false;
3190
3191 case TSK_ExplicitSpecialization:
3192 // C++ DR 259, C++0x [temp.explicit]p4:
3193 // For a given set of template parameters, if an explicit
3194 // instantiation of a template appears after a declaration of
3195 // an explicit specialization for that template, the explicit
3196 // instantiation has no effect.
3197 //
3198 // In C++98/03 mode, we only give an extension warning here, because it
3199 // is not not harmful to try to explicitly instantiate something that
3200 // has been explicitly specialized.
3201 if (!S.getLangOptions().CPlusPlus0x) {
3202 S.Diag(NewLoc, diag::ext_explicit_instantiation_after_specialization)
3203 << PrevDecl;
3204 S.Diag(PrevDecl->getLocation(),
3205 diag::note_previous_template_specialization);
3206 }
3207 SuppressNew = true;
3208 return false;
3209
3210 case TSK_ExplicitInstantiationDeclaration:
3211 // We're explicity instantiating a definition for something for which we
3212 // were previously asked to suppress instantiations. That's fine.
3213 return false;
3214
3215 case TSK_ExplicitInstantiationDefinition:
3216 // C++0x [temp.spec]p5:
3217 // For a given template and a given set of template-arguments,
3218 // - an explicit instantiation definition shall appear at most once
3219 // in a program,
3220 S.Diag(NewLoc, diag::err_explicit_instantiation_duplicate)
3221 << PrevDecl;
3222 S.Diag(PrevPointOfInstantiation,
3223 diag::note_previous_explicit_instantiation);
3224 SuppressNew = true;
3225 return false;
3226 }
3227 break;
3228 }
3229
3230 assert(false && "Missing specialization/instantiation case?");
3231
3232 return false;
3233}
3234
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003235/// \brief Perform semantic analysis for the given function template
3236/// specialization.
3237///
3238/// This routine performs all of the semantic analysis required for an
3239/// explicit function template specialization. On successful completion,
3240/// the function declaration \p FD will become a function template
3241/// specialization.
3242///
3243/// \param FD the function declaration, which will be updated to become a
3244/// function template specialization.
3245///
3246/// \param HasExplicitTemplateArgs whether any template arguments were
3247/// explicitly provided.
3248///
3249/// \param LAngleLoc the location of the left angle bracket ('<'), if
3250/// template arguments were explicitly provided.
3251///
3252/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
3253/// if any.
3254///
3255/// \param NumExplicitTemplateArgs the number of explicitly-provided template
3256/// arguments. This number may be zero even when HasExplicitTemplateArgs is
3257/// true as in, e.g., \c void sort<>(char*, char*);
3258///
3259/// \param RAngleLoc the location of the right angle bracket ('>'), if
3260/// template arguments were explicitly provided.
3261///
3262/// \param PrevDecl the set of declarations that
3263bool
3264Sema::CheckFunctionTemplateSpecialization(FunctionDecl *FD,
3265 bool HasExplicitTemplateArgs,
3266 SourceLocation LAngleLoc,
3267 const TemplateArgument *ExplicitTemplateArgs,
3268 unsigned NumExplicitTemplateArgs,
3269 SourceLocation RAngleLoc,
3270 NamedDecl *&PrevDecl) {
3271 // The set of function template specializations that could match this
3272 // explicit function template specialization.
3273 typedef llvm::SmallVector<FunctionDecl *, 8> CandidateSet;
3274 CandidateSet Candidates;
3275
3276 DeclContext *FDLookupContext = FD->getDeclContext()->getLookupContext();
3277 for (OverloadIterator Ovl(PrevDecl), OvlEnd; Ovl != OvlEnd; ++Ovl) {
3278 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(*Ovl)) {
3279 // Only consider templates found within the same semantic lookup scope as
3280 // FD.
3281 if (!FDLookupContext->Equals(Ovl->getDeclContext()->getLookupContext()))
3282 continue;
3283
3284 // C++ [temp.expl.spec]p11:
3285 // A trailing template-argument can be left unspecified in the
3286 // template-id naming an explicit function template specialization
3287 // provided it can be deduced from the function argument type.
3288 // Perform template argument deduction to determine whether we may be
3289 // specializing this template.
3290 // FIXME: It is somewhat wasteful to build
3291 TemplateDeductionInfo Info(Context);
3292 FunctionDecl *Specialization = 0;
3293 if (TemplateDeductionResult TDK
3294 = DeduceTemplateArguments(FunTmpl, HasExplicitTemplateArgs,
3295 ExplicitTemplateArgs,
3296 NumExplicitTemplateArgs,
3297 FD->getType(),
3298 Specialization,
3299 Info)) {
3300 // FIXME: Template argument deduction failed; record why it failed, so
3301 // that we can provide nifty diagnostics.
3302 (void)TDK;
3303 continue;
3304 }
3305
3306 // Record this candidate.
3307 Candidates.push_back(Specialization);
3308 }
3309 }
3310
Douglas Gregor5de279c2009-09-26 03:41:46 +00003311 // Find the most specialized function template.
3312 FunctionDecl *Specialization = getMostSpecialized(Candidates.data(),
3313 Candidates.size(),
3314 TPOC_Other,
3315 FD->getLocation(),
3316 PartialDiagnostic(diag::err_function_template_spec_no_match)
3317 << FD->getDeclName(),
3318 PartialDiagnostic(diag::err_function_template_spec_ambiguous)
3319 << FD->getDeclName() << HasExplicitTemplateArgs,
3320 PartialDiagnostic(diag::note_function_template_spec_matched));
3321 if (!Specialization)
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003322 return true;
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003323
3324 // FIXME: Check if the prior specialization has a point of instantiation.
Douglas Gregor06db9f52009-10-12 20:18:28 +00003325 // If so, we have run afoul of .
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003326
Douglas Gregor54888652009-10-07 00:13:32 +00003327 // Check the scope of this explicit specialization.
3328 if (CheckTemplateSpecializationScope(*this,
3329 Specialization->getPrimaryTemplate(),
3330 Specialization, FD->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003331 false))
Douglas Gregor54888652009-10-07 00:13:32 +00003332 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00003333
3334 // C++ [temp.expl.spec]p6:
3335 // If a template, a member template or the member of a class template is
3336 // explicitly specialized then that spe- cialization shall be declared
3337 // before the first use of that specialization that would cause an implicit
3338 // instantiation to take place, in every translation unit in which such a
3339 // use occurs; no diagnostic is required.
3340 FunctionTemplateSpecializationInfo *SpecInfo
3341 = Specialization->getTemplateSpecializationInfo();
3342 assert(SpecInfo && "Function template specialization info missing?");
3343 if (SpecInfo->getPointOfInstantiation().isValid()) {
3344 Diag(FD->getLocation(), diag::err_specialization_after_instantiation)
3345 << FD;
3346 Diag(SpecInfo->getPointOfInstantiation(),
3347 diag::note_instantiation_required_here)
3348 << (Specialization->getTemplateSpecializationKind()
3349 != TSK_ImplicitInstantiation);
3350 return true;
3351 }
Douglas Gregor54888652009-10-07 00:13:32 +00003352
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003353 // Mark the prior declaration as an explicit specialization, so that later
3354 // clients know that this is an explicit specialization.
Douglas Gregor06db9f52009-10-12 20:18:28 +00003355 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003356
3357 // Turn the given function declaration into a function template
3358 // specialization, with the template arguments from the previous
3359 // specialization.
3360 FD->setFunctionTemplateSpecialization(Context,
3361 Specialization->getPrimaryTemplate(),
3362 new (Context) TemplateArgumentList(
3363 *Specialization->getTemplateSpecializationArgs()),
3364 /*InsertPos=*/0,
3365 TSK_ExplicitSpecialization);
3366
3367 // The "previous declaration" for this function template specialization is
3368 // the prior function template specialization.
3369 PrevDecl = Specialization;
3370 return false;
3371}
3372
Douglas Gregor86d142a2009-10-08 07:24:58 +00003373/// \brief Perform semantic analysis for the given non-template member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003374/// specialization.
3375///
3376/// This routine performs all of the semantic analysis required for an
3377/// explicit member function specialization. On successful completion,
3378/// the function declaration \p FD will become a member function
3379/// specialization.
3380///
Douglas Gregor86d142a2009-10-08 07:24:58 +00003381/// \param Member the member declaration, which will be updated to become a
3382/// specialization.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003383///
3384/// \param PrevDecl the set of declarations, one of which may be specialized
3385/// by this function specialization.
3386bool
Douglas Gregor86d142a2009-10-08 07:24:58 +00003387Sema::CheckMemberSpecialization(NamedDecl *Member, NamedDecl *&PrevDecl) {
3388 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
3389
3390 // Try to find the member we are instantiating.
3391 NamedDecl *Instantiation = 0;
3392 NamedDecl *InstantiatedFrom = 0;
Douglas Gregor06db9f52009-10-12 20:18:28 +00003393 MemberSpecializationInfo *MSInfo = 0;
3394
Douglas Gregor86d142a2009-10-08 07:24:58 +00003395 if (!PrevDecl) {
3396 // Nowhere to look anyway.
3397 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
3398 for (OverloadIterator Ovl(PrevDecl), OvlEnd; Ovl != OvlEnd; ++Ovl) {
3399 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*Ovl)) {
3400 if (Context.hasSameType(Function->getType(), Method->getType())) {
3401 Instantiation = Method;
3402 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
Douglas Gregor06db9f52009-10-12 20:18:28 +00003403 MSInfo = Method->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00003404 break;
3405 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003406 }
3407 }
Douglas Gregor86d142a2009-10-08 07:24:58 +00003408 } else if (isa<VarDecl>(Member)) {
3409 if (VarDecl *PrevVar = dyn_cast<VarDecl>(PrevDecl))
3410 if (PrevVar->isStaticDataMember()) {
3411 Instantiation = PrevDecl;
3412 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
Douglas Gregor06db9f52009-10-12 20:18:28 +00003413 MSInfo = PrevVar->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00003414 }
3415 } else if (isa<RecordDecl>(Member)) {
3416 if (CXXRecordDecl *PrevRecord = dyn_cast<CXXRecordDecl>(PrevDecl)) {
3417 Instantiation = PrevDecl;
3418 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
Douglas Gregor06db9f52009-10-12 20:18:28 +00003419 MSInfo = PrevRecord->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00003420 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003421 }
3422
3423 if (!Instantiation) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00003424 // There is no previous declaration that matches. Since member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003425 // specializations are always out-of-line, the caller will complain about
3426 // this mismatch later.
3427 return false;
3428 }
3429
Douglas Gregor86d142a2009-10-08 07:24:58 +00003430 // Make sure that this is a specialization of a member.
3431 if (!InstantiatedFrom) {
3432 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
3433 << Member;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003434 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
3435 return true;
3436 }
3437
Douglas Gregor06db9f52009-10-12 20:18:28 +00003438 // C++ [temp.expl.spec]p6:
3439 // If a template, a member template or the member of a class template is
3440 // explicitly specialized then that spe- cialization shall be declared
3441 // before the first use of that specialization that would cause an implicit
3442 // instantiation to take place, in every translation unit in which such a
3443 // use occurs; no diagnostic is required.
3444 assert(MSInfo && "Member specialization info missing?");
3445 if (MSInfo->getPointOfInstantiation().isValid()) {
3446 Diag(Member->getLocation(), diag::err_specialization_after_instantiation)
3447 << Member;
3448 Diag(MSInfo->getPointOfInstantiation(),
3449 diag::note_instantiation_required_here)
3450 << (MSInfo->getTemplateSpecializationKind() != TSK_ImplicitInstantiation);
3451 return true;
3452 }
3453
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003454 // Check the scope of this explicit specialization.
3455 if (CheckTemplateSpecializationScope(*this,
Douglas Gregor86d142a2009-10-08 07:24:58 +00003456 InstantiatedFrom,
3457 Instantiation, Member->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003458 false))
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003459 return true;
Douglas Gregord801b062009-10-07 23:56:10 +00003460
Douglas Gregor86d142a2009-10-08 07:24:58 +00003461 // Note that this is an explicit instantiation of a member.
Douglas Gregorbbe8f462009-10-08 15:14:33 +00003462 // the original declaration to note that it is an explicit specialization
3463 // (if it was previously an implicit instantiation). This latter step
3464 // makes bookkeeping easier.
Douglas Gregor86d142a2009-10-08 07:24:58 +00003465 if (isa<FunctionDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00003466 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
3467 if (InstantiationFunction->getTemplateSpecializationKind() ==
3468 TSK_ImplicitInstantiation) {
3469 InstantiationFunction->setTemplateSpecializationKind(
3470 TSK_ExplicitSpecialization);
3471 InstantiationFunction->setLocation(Member->getLocation());
3472 }
3473
Douglas Gregor86d142a2009-10-08 07:24:58 +00003474 cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
3475 cast<CXXMethodDecl>(InstantiatedFrom),
3476 TSK_ExplicitSpecialization);
3477 } else if (isa<VarDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00003478 VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
3479 if (InstantiationVar->getTemplateSpecializationKind() ==
3480 TSK_ImplicitInstantiation) {
3481 InstantiationVar->setTemplateSpecializationKind(
3482 TSK_ExplicitSpecialization);
3483 InstantiationVar->setLocation(Member->getLocation());
3484 }
3485
Douglas Gregor86d142a2009-10-08 07:24:58 +00003486 Context.setInstantiatedFromStaticDataMember(cast<VarDecl>(Member),
3487 cast<VarDecl>(InstantiatedFrom),
3488 TSK_ExplicitSpecialization);
3489 } else {
3490 assert(isa<CXXRecordDecl>(Member) && "Only member classes remain");
Douglas Gregorbbe8f462009-10-08 15:14:33 +00003491 CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
3492 if (InstantiationClass->getTemplateSpecializationKind() ==
3493 TSK_ImplicitInstantiation) {
3494 InstantiationClass->setTemplateSpecializationKind(
3495 TSK_ExplicitSpecialization);
3496 InstantiationClass->setLocation(Member->getLocation());
3497 }
3498
Douglas Gregor86d142a2009-10-08 07:24:58 +00003499 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
Douglas Gregorbbe8f462009-10-08 15:14:33 +00003500 cast<CXXRecordDecl>(InstantiatedFrom),
3501 TSK_ExplicitSpecialization);
Douglas Gregor86d142a2009-10-08 07:24:58 +00003502 }
3503
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003504 // Save the caller the trouble of having to figure out which declaration
3505 // this specialization matches.
3506 PrevDecl = Instantiation;
3507 return false;
3508}
3509
Douglas Gregore47f5a72009-10-14 23:41:34 +00003510/// \brief Check the scope of an explicit instantiation.
3511static void CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
3512 SourceLocation InstLoc,
3513 bool WasQualifiedName) {
3514 DeclContext *ExpectedContext
3515 = D->getDeclContext()->getEnclosingNamespaceContext()->getLookupContext();
3516 DeclContext *CurContext = S.CurContext->getLookupContext();
3517
3518 // C++0x [temp.explicit]p2:
3519 // An explicit instantiation shall appear in an enclosing namespace of its
3520 // template.
3521 //
3522 // This is DR275, which we do not retroactively apply to C++98/03.
3523 if (S.getLangOptions().CPlusPlus0x &&
3524 !CurContext->Encloses(ExpectedContext)) {
3525 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ExpectedContext))
3526 S.Diag(InstLoc, diag::err_explicit_instantiation_out_of_scope)
3527 << D << NS;
3528 else
3529 S.Diag(InstLoc, diag::err_explicit_instantiation_must_be_global)
3530 << D;
3531 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
3532 return;
3533 }
3534
3535 // C++0x [temp.explicit]p2:
3536 // If the name declared in the explicit instantiation is an unqualified
3537 // name, the explicit instantiation shall appear in the namespace where
3538 // its template is declared or, if that namespace is inline (7.3.1), any
3539 // namespace from its enclosing namespace set.
3540 if (WasQualifiedName)
3541 return;
3542
3543 if (CurContext->Equals(ExpectedContext))
3544 return;
3545
3546 S.Diag(InstLoc, diag::err_explicit_instantiation_unqualified_wrong_namespace)
3547 << D << ExpectedContext;
3548 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
3549}
3550
3551/// \brief Determine whether the given scope specifier has a template-id in it.
3552static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
3553 if (!SS.isSet())
3554 return false;
3555
3556 // C++0x [temp.explicit]p2:
3557 // If the explicit instantiation is for a member function, a member class
3558 // or a static data member of a class template specialization, the name of
3559 // the class template specialization in the qualified-id for the member
3560 // name shall be a simple-template-id.
3561 //
3562 // C++98 has the same restriction, just worded differently.
3563 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
3564 NNS; NNS = NNS->getPrefix())
3565 if (Type *T = NNS->getAsType())
3566 if (isa<TemplateSpecializationType>(T))
3567 return true;
3568
3569 return false;
3570}
3571
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003572// Explicit instantiation of a class template specialization
Douglas Gregor43e75172009-09-04 06:33:52 +00003573// FIXME: Implement extern template semantics
Douglas Gregora1f49972009-05-13 00:25:59 +00003574Sema::DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00003575Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00003576 SourceLocation ExternLoc,
3577 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00003578 unsigned TagSpec,
Douglas Gregora1f49972009-05-13 00:25:59 +00003579 SourceLocation KWLoc,
3580 const CXXScopeSpec &SS,
3581 TemplateTy TemplateD,
3582 SourceLocation TemplateNameLoc,
3583 SourceLocation LAngleLoc,
3584 ASTTemplateArgsPtr TemplateArgsIn,
3585 SourceLocation *TemplateArgLocs,
3586 SourceLocation RAngleLoc,
3587 AttributeList *Attr) {
3588 // Find the class template we're specializing
3589 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump11289f42009-09-09 15:08:12 +00003590 ClassTemplateDecl *ClassTemplate
Douglas Gregora1f49972009-05-13 00:25:59 +00003591 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
3592
3593 // Check that the specialization uses the same tag kind as the
3594 // original template.
3595 TagDecl::TagKind Kind;
3596 switch (TagSpec) {
3597 default: assert(0 && "Unknown tag type!");
3598 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
3599 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
3600 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
3601 }
Douglas Gregord9034f02009-05-14 16:41:31 +00003602 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump11289f42009-09-09 15:08:12 +00003603 Kind, KWLoc,
Douglas Gregord9034f02009-05-14 16:41:31 +00003604 *ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00003605 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora1f49972009-05-13 00:25:59 +00003606 << ClassTemplate
Mike Stump11289f42009-09-09 15:08:12 +00003607 << CodeModificationHint::CreateReplacement(KWLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00003608 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00003609 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregora1f49972009-05-13 00:25:59 +00003610 diag::note_previous_use);
3611 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
3612 }
3613
Douglas Gregore47f5a72009-10-14 23:41:34 +00003614 // C++0x [temp.explicit]p2:
3615 // There are two forms of explicit instantiation: an explicit instantiation
3616 // definition and an explicit instantiation declaration. An explicit
3617 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor54888652009-10-07 00:13:32 +00003618 TemplateSpecializationKind TSK
3619 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
3620 : TSK_ExplicitInstantiationDeclaration;
3621
Douglas Gregora1f49972009-05-13 00:25:59 +00003622 // Translate the parser's template argument list in our AST format.
3623 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
3624 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
3625
3626 // Check that the template argument list is well-formed for this
3627 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003628 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
3629 TemplateArgs.size());
Mike Stump11289f42009-09-09 15:08:12 +00003630 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
Anders Carlssondd096d82009-06-05 02:12:32 +00003631 TemplateArgs.data(), TemplateArgs.size(),
Douglas Gregore3f1f352009-07-01 00:28:38 +00003632 RAngleLoc, false, Converted))
Douglas Gregora1f49972009-05-13 00:25:59 +00003633 return true;
3634
Mike Stump11289f42009-09-09 15:08:12 +00003635 assert((Converted.structuredSize() ==
Douglas Gregora1f49972009-05-13 00:25:59 +00003636 ClassTemplate->getTemplateParameters()->size()) &&
3637 "Converted template argument list is too short!");
Mike Stump11289f42009-09-09 15:08:12 +00003638
Douglas Gregora1f49972009-05-13 00:25:59 +00003639 // Find the class template specialization declaration that
3640 // corresponds to these arguments.
3641 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00003642 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003643 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00003644 Converted.flatSize(),
3645 Context);
Douglas Gregora1f49972009-05-13 00:25:59 +00003646 void *InsertPos = 0;
3647 ClassTemplateSpecializationDecl *PrevDecl
3648 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
3649
Douglas Gregor54888652009-10-07 00:13:32 +00003650 // C++0x [temp.explicit]p2:
3651 // [...] An explicit instantiation shall appear in an enclosing
3652 // namespace of its template. [...]
3653 //
3654 // This is C++ DR 275.
Douglas Gregore47f5a72009-10-14 23:41:34 +00003655 CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
3656 SS.isSet());
Douglas Gregor54888652009-10-07 00:13:32 +00003657
Douglas Gregora1f49972009-05-13 00:25:59 +00003658 ClassTemplateSpecializationDecl *Specialization = 0;
3659
3660 if (PrevDecl) {
Douglas Gregor12e49d32009-10-15 22:53:21 +00003661 bool SuppressNew = false;
3662 if (CheckSpecializationInstantiationRedecl(*this, TemplateNameLoc, TSK,
3663 PrevDecl,
3664 PrevDecl->getSpecializationKind(),
3665 PrevDecl->getPointOfInstantiation(),
3666 SuppressNew))
Douglas Gregora1f49972009-05-13 00:25:59 +00003667 return DeclPtrTy::make(PrevDecl);
Douglas Gregora1f49972009-05-13 00:25:59 +00003668
Douglas Gregor12e49d32009-10-15 22:53:21 +00003669 if (SuppressNew)
Douglas Gregor4aa04b12009-09-11 21:19:12 +00003670 return DeclPtrTy::make(PrevDecl);
Douglas Gregor12e49d32009-10-15 22:53:21 +00003671
Douglas Gregor4aa04b12009-09-11 21:19:12 +00003672 if (PrevDecl->getSpecializationKind() == TSK_ImplicitInstantiation ||
3673 PrevDecl->getSpecializationKind() == TSK_Undeclared) {
3674 // Since the only prior class template specialization with these
3675 // arguments was referenced but not declared, reuse that
3676 // declaration node as our own, updating its source location to
3677 // reflect our new declaration.
3678 Specialization = PrevDecl;
3679 Specialization->setLocation(TemplateNameLoc);
3680 PrevDecl = 0;
3681 }
Douglas Gregor12e49d32009-10-15 22:53:21 +00003682 }
Douglas Gregor4aa04b12009-09-11 21:19:12 +00003683
3684 if (!Specialization) {
Douglas Gregora1f49972009-05-13 00:25:59 +00003685 // Create a new class template specialization declaration node for
3686 // this explicit specialization.
3687 Specialization
Mike Stump11289f42009-09-09 15:08:12 +00003688 = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregora1f49972009-05-13 00:25:59 +00003689 ClassTemplate->getDeclContext(),
3690 TemplateNameLoc,
3691 ClassTemplate,
Douglas Gregor4aa04b12009-09-11 21:19:12 +00003692 Converted, PrevDecl);
Douglas Gregora1f49972009-05-13 00:25:59 +00003693
Douglas Gregor4aa04b12009-09-11 21:19:12 +00003694 if (PrevDecl) {
3695 // Remove the previous declaration from the folding set, since we want
3696 // to introduce a new declaration.
3697 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
3698 ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
3699 }
3700
3701 // Insert the new specialization.
3702 ClassTemplate->getSpecializations().InsertNode(Specialization, InsertPos);
Douglas Gregora1f49972009-05-13 00:25:59 +00003703 }
3704
3705 // Build the fully-sugared type for this explicit instantiation as
3706 // the user wrote in the explicit instantiation itself. This means
3707 // that we'll pretty-print the type retrieved from the
3708 // specialization's declaration the way that the user actually wrote
3709 // the explicit instantiation, rather than formatting the name based
3710 // on the "canonical" representation used to store the template
3711 // arguments in the specialization.
Mike Stump11289f42009-09-09 15:08:12 +00003712 QualType WrittenTy
3713 = Context.getTemplateSpecializationType(Name,
Anders Carlsson03c9e872009-06-05 02:45:24 +00003714 TemplateArgs.data(),
Douglas Gregora1f49972009-05-13 00:25:59 +00003715 TemplateArgs.size(),
3716 Context.getTypeDeclType(Specialization));
3717 Specialization->setTypeAsWritten(WrittenTy);
3718 TemplateArgsIn.release();
3719
3720 // Add the explicit instantiation into its lexical context. However,
3721 // since explicit instantiations are never found by name lookup, we
3722 // just put it into the declaration context directly.
3723 Specialization->setLexicalDeclContext(CurContext);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003724 CurContext->addDecl(Specialization);
Douglas Gregora1f49972009-05-13 00:25:59 +00003725
John McCall1806c272009-09-11 07:25:08 +00003726 Specialization->setPointOfInstantiation(TemplateNameLoc);
3727
Douglas Gregora1f49972009-05-13 00:25:59 +00003728 // C++ [temp.explicit]p3:
Douglas Gregora1f49972009-05-13 00:25:59 +00003729 // A definition of a class template or class member template
3730 // shall be in scope at the point of the explicit instantiation of
3731 // the class template or class member template.
3732 //
3733 // This check comes when we actually try to perform the
3734 // instantiation.
Douglas Gregor12e49d32009-10-15 22:53:21 +00003735 ClassTemplateSpecializationDecl *Def
3736 = cast_or_null<ClassTemplateSpecializationDecl>(
3737 Specialization->getDefinition(Context));
3738 if (!Def)
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003739 InstantiateClassTemplateSpecialization(Specialization, TSK);
Douglas Gregor85673582009-05-18 17:01:57 +00003740 else // Instantiate the members of this class template specialization.
Douglas Gregor12e49d32009-10-15 22:53:21 +00003741 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
Douglas Gregora1f49972009-05-13 00:25:59 +00003742
3743 return DeclPtrTy::make(Specialization);
3744}
3745
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003746// Explicit instantiation of a member class of a class template.
3747Sema::DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00003748Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00003749 SourceLocation ExternLoc,
3750 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00003751 unsigned TagSpec,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003752 SourceLocation KWLoc,
3753 const CXXScopeSpec &SS,
3754 IdentifierInfo *Name,
3755 SourceLocation NameLoc,
3756 AttributeList *Attr) {
3757
Douglas Gregord6ab8742009-05-28 23:31:59 +00003758 bool Owned = false;
John McCall7f41d982009-09-11 04:59:25 +00003759 bool IsDependent = false;
John McCall9bb74a52009-07-31 02:45:11 +00003760 DeclPtrTy TagD = ActOnTag(S, TagSpec, Action::TUK_Reference,
Douglas Gregore93e46c2009-07-22 23:48:44 +00003761 KWLoc, SS, Name, NameLoc, Attr, AS_none,
John McCall7f41d982009-09-11 04:59:25 +00003762 MultiTemplateParamsArg(*this, 0, 0),
3763 Owned, IsDependent);
3764 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
3765
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003766 if (!TagD)
3767 return true;
3768
3769 TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
3770 if (Tag->isEnum()) {
3771 Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
3772 << Context.getTypeDeclType(Tag);
3773 return true;
3774 }
3775
Douglas Gregorb8006faf2009-05-27 17:30:49 +00003776 if (Tag->isInvalidDecl())
3777 return true;
Douglas Gregore47f5a72009-10-14 23:41:34 +00003778
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003779 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
3780 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
3781 if (!Pattern) {
3782 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
3783 << Context.getTypeDeclType(Record);
3784 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
3785 return true;
3786 }
3787
Douglas Gregore47f5a72009-10-14 23:41:34 +00003788 // C++0x [temp.explicit]p2:
3789 // If the explicit instantiation is for a class or member class, the
3790 // elaborated-type-specifier in the declaration shall include a
3791 // simple-template-id.
3792 //
3793 // C++98 has the same restriction, just worded differently.
3794 if (!ScopeSpecifierHasTemplateId(SS))
3795 Diag(TemplateLoc, diag::err_explicit_instantiation_without_qualified_id)
3796 << Record << SS.getRange();
3797
3798 // C++0x [temp.explicit]p2:
3799 // There are two forms of explicit instantiation: an explicit instantiation
3800 // definition and an explicit instantiation declaration. An explicit
3801 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor5d851972009-10-14 21:46:58 +00003802 TemplateSpecializationKind TSK
3803 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
3804 : TSK_ExplicitInstantiationDeclaration;
3805
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003806 // C++0x [temp.explicit]p2:
3807 // [...] An explicit instantiation shall appear in an enclosing
3808 // namespace of its template. [...]
3809 //
3810 // This is C++ DR 275.
Douglas Gregore47f5a72009-10-14 23:41:34 +00003811 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003812
3813 // Verify that it is okay to explicitly instantiate here.
Douglas Gregor8f003d02009-10-15 18:07:02 +00003814 CXXRecordDecl *PrevDecl
3815 = cast_or_null<CXXRecordDecl>(Record->getPreviousDeclaration());
3816 if (!PrevDecl && Record->getDefinition(Context))
3817 PrevDecl = Record;
3818 if (PrevDecl) {
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003819 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
3820 bool SuppressNew = false;
3821 assert(MSInfo && "No member specialization information?");
3822 if (CheckSpecializationInstantiationRedecl(*this, TemplateLoc, TSK,
3823 PrevDecl,
3824 MSInfo->getTemplateSpecializationKind(),
3825 MSInfo->getPointOfInstantiation(),
3826 SuppressNew))
3827 return true;
3828 if (SuppressNew)
3829 return TagD;
3830 }
3831
Douglas Gregor12e49d32009-10-15 22:53:21 +00003832 CXXRecordDecl *RecordDef
3833 = cast_or_null<CXXRecordDecl>(Record->getDefinition(Context));
3834 if (!RecordDef) {
Douglas Gregor68edf132009-10-15 12:53:22 +00003835 // C++ [temp.explicit]p3:
3836 // A definition of a member class of a class template shall be in scope
3837 // at the point of an explicit instantiation of the member class.
3838 CXXRecordDecl *Def
3839 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition(Context));
3840 if (!Def) {
Douglas Gregora8b89d22009-10-15 14:05:49 +00003841 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
3842 << 0 << Record->getDeclName() << Record->getDeclContext();
Douglas Gregor68edf132009-10-15 12:53:22 +00003843 Diag(Pattern->getLocation(), diag::note_forward_declaration)
3844 << Pattern;
3845 return true;
Douglas Gregor12e49d32009-10-15 22:53:21 +00003846 } else if (InstantiateClass(NameLoc, Record, Def,
Douglas Gregor68edf132009-10-15 12:53:22 +00003847 getTemplateInstantiationArgs(Record),
3848 TSK))
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003849 return true;
John McCall76d824f2009-08-25 22:02:44 +00003850 } else // Instantiate all of the members of the class.
Douglas Gregor12e49d32009-10-15 22:53:21 +00003851 InstantiateClassMembers(NameLoc, RecordDef,
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003852 getTemplateInstantiationArgs(Record), TSK);
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003853
Mike Stump87c57ac2009-05-16 07:39:55 +00003854 // FIXME: We don't have any representation for explicit instantiations of
3855 // member classes. Such a representation is not needed for compilation, but it
3856 // should be available for clients that want to see all of the declarations in
3857 // the source code.
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003858 return TagD;
3859}
3860
Douglas Gregor450f00842009-09-25 18:43:00 +00003861Sema::DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
3862 SourceLocation ExternLoc,
3863 SourceLocation TemplateLoc,
3864 Declarator &D) {
3865 // Explicit instantiations always require a name.
3866 DeclarationName Name = GetNameForDeclarator(D);
3867 if (!Name) {
3868 if (!D.isInvalidType())
3869 Diag(D.getDeclSpec().getSourceRange().getBegin(),
3870 diag::err_explicit_instantiation_requires_name)
3871 << D.getDeclSpec().getSourceRange()
3872 << D.getSourceRange();
3873
3874 return true;
3875 }
3876
3877 // The scope passed in may not be a decl scope. Zip up the scope tree until
3878 // we find one that is.
3879 while ((S->getFlags() & Scope::DeclScope) == 0 ||
3880 (S->getFlags() & Scope::TemplateParamScope) != 0)
3881 S = S->getParent();
3882
3883 // Determine the type of the declaration.
3884 QualType R = GetTypeForDeclarator(D, S, 0);
3885 if (R.isNull())
3886 return true;
3887
3888 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
3889 // Cannot explicitly instantiate a typedef.
3890 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
3891 << Name;
3892 return true;
3893 }
3894
Douglas Gregor3c74d412009-10-14 20:14:33 +00003895 // C++0x [temp.explicit]p1:
3896 // [...] An explicit instantiation of a function template shall not use the
3897 // inline or constexpr specifiers.
3898 // Presumably, this also applies to member functions of class templates as
3899 // well.
3900 if (D.getDeclSpec().isInlineSpecified() && getLangOptions().CPlusPlus0x)
3901 Diag(D.getDeclSpec().getInlineSpecLoc(),
3902 diag::err_explicit_instantiation_inline)
3903 << CodeModificationHint::CreateRemoval(
3904 SourceRange(D.getDeclSpec().getInlineSpecLoc()));
3905
3906 // FIXME: check for constexpr specifier.
3907
Douglas Gregore47f5a72009-10-14 23:41:34 +00003908 // C++0x [temp.explicit]p2:
3909 // There are two forms of explicit instantiation: an explicit instantiation
3910 // definition and an explicit instantiation declaration. An explicit
3911 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor450f00842009-09-25 18:43:00 +00003912 TemplateSpecializationKind TSK
3913 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
3914 : TSK_ExplicitInstantiationDeclaration;
Douglas Gregore47f5a72009-10-14 23:41:34 +00003915
John McCall9f3059a2009-10-09 21:13:30 +00003916 LookupResult Previous;
3917 LookupParsedName(Previous, S, &D.getCXXScopeSpec(),
3918 Name, LookupOrdinaryName);
Douglas Gregor450f00842009-09-25 18:43:00 +00003919
3920 if (!R->isFunctionType()) {
3921 // C++ [temp.explicit]p1:
3922 // A [...] static data member of a class template can be explicitly
3923 // instantiated from the member definition associated with its class
3924 // template.
3925 if (Previous.isAmbiguous()) {
3926 return DiagnoseAmbiguousLookup(Previous, Name, D.getIdentifierLoc(),
3927 D.getSourceRange());
3928 }
3929
John McCall9f3059a2009-10-09 21:13:30 +00003930 VarDecl *Prev = dyn_cast_or_null<VarDecl>(
3931 Previous.getAsSingleDecl(Context));
Douglas Gregor450f00842009-09-25 18:43:00 +00003932 if (!Prev || !Prev->isStaticDataMember()) {
3933 // We expect to see a data data member here.
3934 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
3935 << Name;
3936 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
3937 P != PEnd; ++P)
John McCall9f3059a2009-10-09 21:13:30 +00003938 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor450f00842009-09-25 18:43:00 +00003939 return true;
3940 }
3941
3942 if (!Prev->getInstantiatedFromStaticDataMember()) {
3943 // FIXME: Check for explicit specialization?
3944 Diag(D.getIdentifierLoc(),
3945 diag::err_explicit_instantiation_data_member_not_instantiated)
3946 << Prev;
3947 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
3948 // FIXME: Can we provide a note showing where this was declared?
3949 return true;
3950 }
3951
Douglas Gregore47f5a72009-10-14 23:41:34 +00003952 // C++0x [temp.explicit]p2:
3953 // If the explicit instantiation is for a member function, a member class
3954 // or a static data member of a class template specialization, the name of
3955 // the class template specialization in the qualified-id for the member
3956 // name shall be a simple-template-id.
3957 //
3958 // C++98 has the same restriction, just worded differently.
3959 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
3960 Diag(D.getIdentifierLoc(),
3961 diag::err_explicit_instantiation_without_qualified_id)
3962 << Prev << D.getCXXScopeSpec().getRange();
3963
3964 // Check the scope of this explicit instantiation.
3965 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
3966
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003967 // Verify that it is okay to explicitly instantiate here.
3968 MemberSpecializationInfo *MSInfo = Prev->getMemberSpecializationInfo();
3969 assert(MSInfo && "Missing static data member specialization info?");
3970 bool SuppressNew = false;
3971 if (CheckSpecializationInstantiationRedecl(*this, D.getIdentifierLoc(), TSK,
3972 Prev,
3973 MSInfo->getTemplateSpecializationKind(),
3974 MSInfo->getPointOfInstantiation(),
3975 SuppressNew))
3976 return true;
3977 if (SuppressNew)
3978 return DeclPtrTy();
3979
Douglas Gregor450f00842009-09-25 18:43:00 +00003980 // Instantiate static data member.
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00003981 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregor450f00842009-09-25 18:43:00 +00003982 if (TSK == TSK_ExplicitInstantiationDefinition)
Douglas Gregora8b89d22009-10-15 14:05:49 +00003983 InstantiateStaticDataMemberDefinition(D.getIdentifierLoc(), Prev, false,
3984 /*DefinitionRequired=*/true);
Douglas Gregor450f00842009-09-25 18:43:00 +00003985
3986 // FIXME: Create an ExplicitInstantiation node?
3987 return DeclPtrTy();
3988 }
3989
Douglas Gregor0e876e02009-09-25 23:53:26 +00003990 // If the declarator is a template-id, translate the parser's template
3991 // argument list into our AST format.
Douglas Gregord90fd522009-09-25 21:45:23 +00003992 bool HasExplicitTemplateArgs = false;
3993 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
3994 if (D.getKind() == Declarator::DK_TemplateId) {
3995 TemplateIdAnnotation *TemplateId = D.getTemplateId();
3996 ASTTemplateArgsPtr TemplateArgsPtr(*this,
3997 TemplateId->getTemplateArgs(),
3998 TemplateId->getTemplateArgIsType(),
3999 TemplateId->NumArgs);
4000 translateTemplateArguments(TemplateArgsPtr,
4001 TemplateId->getTemplateArgLocations(),
4002 TemplateArgs);
4003 HasExplicitTemplateArgs = true;
Douglas Gregorf343fd82009-10-01 23:51:25 +00004004 TemplateArgsPtr.release();
Douglas Gregord90fd522009-09-25 21:45:23 +00004005 }
Douglas Gregor0e876e02009-09-25 23:53:26 +00004006
Douglas Gregor450f00842009-09-25 18:43:00 +00004007 // C++ [temp.explicit]p1:
4008 // A [...] function [...] can be explicitly instantiated from its template.
4009 // A member function [...] of a class template can be explicitly
4010 // instantiated from the member definition associated with its class
4011 // template.
Douglas Gregor450f00842009-09-25 18:43:00 +00004012 llvm::SmallVector<FunctionDecl *, 8> Matches;
4013 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
4014 P != PEnd; ++P) {
4015 NamedDecl *Prev = *P;
Douglas Gregord90fd522009-09-25 21:45:23 +00004016 if (!HasExplicitTemplateArgs) {
4017 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
4018 if (Context.hasSameUnqualifiedType(Method->getType(), R)) {
4019 Matches.clear();
4020 Matches.push_back(Method);
4021 break;
4022 }
Douglas Gregor450f00842009-09-25 18:43:00 +00004023 }
4024 }
4025
4026 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
4027 if (!FunTmpl)
4028 continue;
4029
4030 TemplateDeductionInfo Info(Context);
4031 FunctionDecl *Specialization = 0;
4032 if (TemplateDeductionResult TDK
Douglas Gregord90fd522009-09-25 21:45:23 +00004033 = DeduceTemplateArguments(FunTmpl, HasExplicitTemplateArgs,
4034 TemplateArgs.data(), TemplateArgs.size(),
Douglas Gregor450f00842009-09-25 18:43:00 +00004035 R, Specialization, Info)) {
4036 // FIXME: Keep track of almost-matches?
4037 (void)TDK;
4038 continue;
4039 }
4040
4041 Matches.push_back(Specialization);
4042 }
4043
4044 // Find the most specialized function template specialization.
4045 FunctionDecl *Specialization
4046 = getMostSpecialized(Matches.data(), Matches.size(), TPOC_Other,
4047 D.getIdentifierLoc(),
4048 PartialDiagnostic(diag::err_explicit_instantiation_not_known) << Name,
4049 PartialDiagnostic(diag::err_explicit_instantiation_ambiguous) << Name,
4050 PartialDiagnostic(diag::note_explicit_instantiation_candidate));
4051
4052 if (!Specialization)
4053 return true;
4054
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004055 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
Douglas Gregor450f00842009-09-25 18:43:00 +00004056 Diag(D.getIdentifierLoc(),
4057 diag::err_explicit_instantiation_member_function_not_instantiated)
4058 << Specialization
4059 << (Specialization->getTemplateSpecializationKind() ==
4060 TSK_ExplicitSpecialization);
4061 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
4062 return true;
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004063 }
Douglas Gregore47f5a72009-10-14 23:41:34 +00004064
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004065 FunctionDecl *PrevDecl = Specialization->getPreviousDeclaration();
Douglas Gregor8f003d02009-10-15 18:07:02 +00004066 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
4067 PrevDecl = Specialization;
4068
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004069 if (PrevDecl) {
4070 bool SuppressNew = false;
4071 if (CheckSpecializationInstantiationRedecl(*this, D.getIdentifierLoc(), TSK,
4072 PrevDecl,
4073 PrevDecl->getTemplateSpecializationKind(),
4074 PrevDecl->getPointOfInstantiation(),
4075 SuppressNew))
4076 return true;
4077
4078 // FIXME: We may still want to build some representation of this
4079 // explicit specialization.
4080 if (SuppressNew)
4081 return DeclPtrTy();
4082 }
4083
4084 if (TSK == TSK_ExplicitInstantiationDefinition)
4085 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization,
4086 false, /*DefinitionRequired=*/true);
4087
4088 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
4089
Douglas Gregore47f5a72009-10-14 23:41:34 +00004090 // C++0x [temp.explicit]p2:
4091 // If the explicit instantiation is for a member function, a member class
4092 // or a static data member of a class template specialization, the name of
4093 // the class template specialization in the qualified-id for the member
4094 // name shall be a simple-template-id.
4095 //
4096 // C++98 has the same restriction, just worded differently.
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004097 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
Douglas Gregore47f5a72009-10-14 23:41:34 +00004098 if (D.getKind() != Declarator::DK_TemplateId && !FunTmpl &&
4099 D.getCXXScopeSpec().isSet() &&
4100 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
4101 Diag(D.getIdentifierLoc(),
4102 diag::err_explicit_instantiation_without_qualified_id)
4103 << Specialization << D.getCXXScopeSpec().getRange();
4104
4105 CheckExplicitInstantiationScope(*this,
4106 FunTmpl? (NamedDecl *)FunTmpl
4107 : Specialization->getInstantiatedFromMemberFunction(),
4108 D.getIdentifierLoc(),
4109 D.getCXXScopeSpec().isSet());
4110
Douglas Gregor450f00842009-09-25 18:43:00 +00004111 // FIXME: Create some kind of ExplicitInstantiationDecl here.
4112 return DeclPtrTy();
4113}
4114
Douglas Gregor333489b2009-03-27 23:10:48 +00004115Sema::TypeResult
John McCall7f41d982009-09-11 04:59:25 +00004116Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
4117 const CXXScopeSpec &SS, IdentifierInfo *Name,
4118 SourceLocation TagLoc, SourceLocation NameLoc) {
4119 // This has to hold, because SS is expected to be defined.
4120 assert(Name && "Expected a name in a dependent tag");
4121
4122 NestedNameSpecifier *NNS
4123 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
4124 if (!NNS)
4125 return true;
4126
4127 QualType T = CheckTypenameType(NNS, *Name, SourceRange(TagLoc, NameLoc));
4128 if (T.isNull())
4129 return true;
4130
4131 TagDecl::TagKind TagKind = TagDecl::getTagKindForTypeSpec(TagSpec);
4132 QualType ElabType = Context.getElaboratedType(T, TagKind);
4133
4134 return ElabType.getAsOpaquePtr();
4135}
4136
4137Sema::TypeResult
Douglas Gregor333489b2009-03-27 23:10:48 +00004138Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
4139 const IdentifierInfo &II, SourceLocation IdLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00004140 NestedNameSpecifier *NNS
Douglas Gregor333489b2009-03-27 23:10:48 +00004141 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
4142 if (!NNS)
4143 return true;
4144
4145 QualType T = CheckTypenameType(NNS, II, SourceRange(TypenameLoc, IdLoc));
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00004146 if (T.isNull())
4147 return true;
Douglas Gregor333489b2009-03-27 23:10:48 +00004148 return T.getAsOpaquePtr();
4149}
4150
Douglas Gregordce2b622009-04-01 00:28:59 +00004151Sema::TypeResult
4152Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
4153 SourceLocation TemplateLoc, TypeTy *Ty) {
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00004154 QualType T = GetTypeFromParser(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00004155 NestedNameSpecifier *NNS
Douglas Gregordce2b622009-04-01 00:28:59 +00004156 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Mike Stump11289f42009-09-09 15:08:12 +00004157 const TemplateSpecializationType *TemplateId
John McCall9dd450b2009-09-21 23:43:11 +00004158 = T->getAs<TemplateSpecializationType>();
Douglas Gregordce2b622009-04-01 00:28:59 +00004159 assert(TemplateId && "Expected a template specialization type");
4160
Douglas Gregor12bbfe12009-09-02 13:05:45 +00004161 if (computeDeclContext(SS, false)) {
4162 // If we can compute a declaration context, then the "typename"
4163 // keyword was superfluous. Just build a QualifiedNameType to keep
4164 // track of the nested-name-specifier.
Mike Stump11289f42009-09-09 15:08:12 +00004165
Douglas Gregor12bbfe12009-09-02 13:05:45 +00004166 // FIXME: Note that the QualifiedNameType had the "typename" keyword!
4167 return Context.getQualifiedNameType(NNS, T).getAsOpaquePtr();
4168 }
Mike Stump11289f42009-09-09 15:08:12 +00004169
Douglas Gregor12bbfe12009-09-02 13:05:45 +00004170 return Context.getTypenameType(NNS, TemplateId).getAsOpaquePtr();
Douglas Gregordce2b622009-04-01 00:28:59 +00004171}
4172
Douglas Gregor333489b2009-03-27 23:10:48 +00004173/// \brief Build the type that describes a C++ typename specifier,
4174/// e.g., "typename T::type".
4175QualType
4176Sema::CheckTypenameType(NestedNameSpecifier *NNS, const IdentifierInfo &II,
4177 SourceRange Range) {
Douglas Gregorc9f9b862009-05-11 19:58:34 +00004178 CXXRecordDecl *CurrentInstantiation = 0;
4179 if (NNS->isDependent()) {
4180 CurrentInstantiation = getCurrentInstantiationOf(NNS);
Douglas Gregor333489b2009-03-27 23:10:48 +00004181
Douglas Gregorc9f9b862009-05-11 19:58:34 +00004182 // If the nested-name-specifier does not refer to the current
4183 // instantiation, then build a typename type.
4184 if (!CurrentInstantiation)
4185 return Context.getTypenameType(NNS, &II);
Mike Stump11289f42009-09-09 15:08:12 +00004186
Douglas Gregorc707da62009-09-02 13:12:51 +00004187 // The nested-name-specifier refers to the current instantiation, so the
4188 // "typename" keyword itself is superfluous. In C++03, the program is
Mike Stump11289f42009-09-09 15:08:12 +00004189 // actually ill-formed. However, DR 382 (in C++0x CD1) allows such
Douglas Gregorc707da62009-09-02 13:12:51 +00004190 // extraneous "typename" keywords, and we retroactively apply this DR to
4191 // C++03 code.
Douglas Gregorc9f9b862009-05-11 19:58:34 +00004192 }
Douglas Gregor333489b2009-03-27 23:10:48 +00004193
Douglas Gregorc9f9b862009-05-11 19:58:34 +00004194 DeclContext *Ctx = 0;
4195
4196 if (CurrentInstantiation)
4197 Ctx = CurrentInstantiation;
4198 else {
4199 CXXScopeSpec SS;
4200 SS.setScopeRep(NNS);
4201 SS.setRange(Range);
4202 if (RequireCompleteDeclContext(SS))
4203 return QualType();
4204
4205 Ctx = computeDeclContext(SS);
4206 }
Douglas Gregor333489b2009-03-27 23:10:48 +00004207 assert(Ctx && "No declaration context?");
4208
4209 DeclarationName Name(&II);
John McCall9f3059a2009-10-09 21:13:30 +00004210 LookupResult Result;
4211 LookupQualifiedName(Result, Ctx, Name, LookupOrdinaryName, false);
Douglas Gregor333489b2009-03-27 23:10:48 +00004212 unsigned DiagID = 0;
4213 Decl *Referenced = 0;
4214 switch (Result.getKind()) {
4215 case LookupResult::NotFound:
Douglas Gregore40876a2009-10-13 21:16:44 +00004216 DiagID = diag::err_typename_nested_not_found;
Douglas Gregor333489b2009-03-27 23:10:48 +00004217 break;
4218
4219 case LookupResult::Found:
John McCall9f3059a2009-10-09 21:13:30 +00004220 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
Douglas Gregor333489b2009-03-27 23:10:48 +00004221 // We found a type. Build a QualifiedNameType, since the
4222 // typename-specifier was just sugar. FIXME: Tell
4223 // QualifiedNameType that it has a "typename" prefix.
4224 return Context.getQualifiedNameType(NNS, Context.getTypeDeclType(Type));
4225 }
4226
4227 DiagID = diag::err_typename_nested_not_type;
John McCall9f3059a2009-10-09 21:13:30 +00004228 Referenced = Result.getFoundDecl();
Douglas Gregor333489b2009-03-27 23:10:48 +00004229 break;
4230
4231 case LookupResult::FoundOverloaded:
4232 DiagID = diag::err_typename_nested_not_type;
4233 Referenced = *Result.begin();
4234 break;
4235
John McCall6538c932009-10-10 05:48:19 +00004236 case LookupResult::Ambiguous:
Douglas Gregor333489b2009-03-27 23:10:48 +00004237 DiagnoseAmbiguousLookup(Result, Name, Range.getEnd(), Range);
4238 return QualType();
4239 }
4240
4241 // If we get here, it's because name lookup did not find a
4242 // type. Emit an appropriate diagnostic and return an error.
Douglas Gregore40876a2009-10-13 21:16:44 +00004243 Diag(Range.getEnd(), DiagID) << Range << Name << Ctx;
Douglas Gregor333489b2009-03-27 23:10:48 +00004244 if (Referenced)
4245 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
4246 << Name;
4247 return QualType();
4248}
Douglas Gregor15acfb92009-08-06 16:20:37 +00004249
4250namespace {
4251 // See Sema::RebuildTypeInCurrentInstantiation
Mike Stump11289f42009-09-09 15:08:12 +00004252 class VISIBILITY_HIDDEN CurrentInstantiationRebuilder
4253 : public TreeTransform<CurrentInstantiationRebuilder> {
Douglas Gregor15acfb92009-08-06 16:20:37 +00004254 SourceLocation Loc;
4255 DeclarationName Entity;
Mike Stump11289f42009-09-09 15:08:12 +00004256
Douglas Gregor15acfb92009-08-06 16:20:37 +00004257 public:
Mike Stump11289f42009-09-09 15:08:12 +00004258 CurrentInstantiationRebuilder(Sema &SemaRef,
Douglas Gregor15acfb92009-08-06 16:20:37 +00004259 SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00004260 DeclarationName Entity)
4261 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
Douglas Gregor15acfb92009-08-06 16:20:37 +00004262 Loc(Loc), Entity(Entity) { }
Mike Stump11289f42009-09-09 15:08:12 +00004263
4264 /// \brief Determine whether the given type \p T has already been
Douglas Gregor15acfb92009-08-06 16:20:37 +00004265 /// transformed.
4266 ///
4267 /// For the purposes of type reconstruction, a type has already been
4268 /// transformed if it is NULL or if it is not dependent.
4269 bool AlreadyTransformed(QualType T) {
4270 return T.isNull() || !T->isDependentType();
4271 }
Mike Stump11289f42009-09-09 15:08:12 +00004272
4273 /// \brief Returns the location of the entity whose type is being
Douglas Gregor15acfb92009-08-06 16:20:37 +00004274 /// rebuilt.
4275 SourceLocation getBaseLocation() { return Loc; }
Mike Stump11289f42009-09-09 15:08:12 +00004276
Douglas Gregor15acfb92009-08-06 16:20:37 +00004277 /// \brief Returns the name of the entity whose type is being rebuilt.
4278 DeclarationName getBaseEntity() { return Entity; }
Mike Stump11289f42009-09-09 15:08:12 +00004279
Douglas Gregor15acfb92009-08-06 16:20:37 +00004280 /// \brief Transforms an expression by returning the expression itself
4281 /// (an identity function).
4282 ///
4283 /// FIXME: This is completely unsafe; we will need to actually clone the
4284 /// expressions.
4285 Sema::OwningExprResult TransformExpr(Expr *E) {
4286 return getSema().Owned(E);
4287 }
Mike Stump11289f42009-09-09 15:08:12 +00004288
Douglas Gregor15acfb92009-08-06 16:20:37 +00004289 /// \brief Transforms a typename type by determining whether the type now
4290 /// refers to a member of the current instantiation, and then
4291 /// type-checking and building a QualifiedNameType (when possible).
John McCall550e0c22009-10-21 00:40:46 +00004292 QualType TransformTypenameType(TypeLocBuilder &TLB, TypenameTypeLoc TL);
4293 QualType TransformTypenameType(TypenameType *T);
Douglas Gregor15acfb92009-08-06 16:20:37 +00004294 };
4295}
4296
Mike Stump11289f42009-09-09 15:08:12 +00004297QualType
John McCall550e0c22009-10-21 00:40:46 +00004298CurrentInstantiationRebuilder::TransformTypenameType(TypeLocBuilder &TLB,
4299 TypenameTypeLoc TL) {
4300 QualType Result = TransformTypenameType(TL.getTypePtr());
4301 if (Result.isNull())
4302 return QualType();
4303
4304 TypenameTypeLoc NewTL = TLB.push<TypenameTypeLoc>(Result);
4305 NewTL.setNameLoc(TL.getNameLoc());
4306
4307 return Result;
4308}
4309
4310QualType
4311CurrentInstantiationRebuilder::TransformTypenameType(TypenameType *T) {
4312
Douglas Gregor15acfb92009-08-06 16:20:37 +00004313 NestedNameSpecifier *NNS
4314 = TransformNestedNameSpecifier(T->getQualifier(),
4315 /*FIXME:*/SourceRange(getBaseLocation()));
4316 if (!NNS)
4317 return QualType();
4318
4319 // If the nested-name-specifier did not change, and we cannot compute the
4320 // context corresponding to the nested-name-specifier, then this
4321 // typename type will not change; exit early.
4322 CXXScopeSpec SS;
4323 SS.setRange(SourceRange(getBaseLocation()));
4324 SS.setScopeRep(NNS);
4325 if (NNS == T->getQualifier() && getSema().computeDeclContext(SS) == 0)
4326 return QualType(T, 0);
Mike Stump11289f42009-09-09 15:08:12 +00004327
4328 // Rebuild the typename type, which will probably turn into a
Douglas Gregor15acfb92009-08-06 16:20:37 +00004329 // QualifiedNameType.
4330 if (const TemplateSpecializationType *TemplateId = T->getTemplateId()) {
Mike Stump11289f42009-09-09 15:08:12 +00004331 QualType NewTemplateId
Douglas Gregor15acfb92009-08-06 16:20:37 +00004332 = TransformType(QualType(TemplateId, 0));
4333 if (NewTemplateId.isNull())
4334 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00004335
Douglas Gregor15acfb92009-08-06 16:20:37 +00004336 if (NNS == T->getQualifier() &&
4337 NewTemplateId == QualType(TemplateId, 0))
4338 return QualType(T, 0);
Mike Stump11289f42009-09-09 15:08:12 +00004339
Douglas Gregor15acfb92009-08-06 16:20:37 +00004340 return getDerived().RebuildTypenameType(NNS, NewTemplateId);
4341 }
Mike Stump11289f42009-09-09 15:08:12 +00004342
Douglas Gregor15acfb92009-08-06 16:20:37 +00004343 return getDerived().RebuildTypenameType(NNS, T->getIdentifier());
4344}
4345
4346/// \brief Rebuilds a type within the context of the current instantiation.
4347///
Mike Stump11289f42009-09-09 15:08:12 +00004348/// The type \p T is part of the type of an out-of-line member definition of
Douglas Gregor15acfb92009-08-06 16:20:37 +00004349/// a class template (or class template partial specialization) that was parsed
Mike Stump11289f42009-09-09 15:08:12 +00004350/// and constructed before we entered the scope of the class template (or
Douglas Gregor15acfb92009-08-06 16:20:37 +00004351/// partial specialization thereof). This routine will rebuild that type now
4352/// that we have entered the declarator's scope, which may produce different
4353/// canonical types, e.g.,
4354///
4355/// \code
4356/// template<typename T>
4357/// struct X {
4358/// typedef T* pointer;
4359/// pointer data();
4360/// };
4361///
4362/// template<typename T>
4363/// typename X<T>::pointer X<T>::data() { ... }
4364/// \endcode
4365///
4366/// Here, the type "typename X<T>::pointer" will be created as a TypenameType,
4367/// since we do not know that we can look into X<T> when we parsed the type.
4368/// This function will rebuild the type, performing the lookup of "pointer"
4369/// in X<T> and returning a QualifiedNameType whose canonical type is the same
4370/// as the canonical type of T*, allowing the return types of the out-of-line
4371/// definition and the declaration to match.
4372QualType Sema::RebuildTypeInCurrentInstantiation(QualType T, SourceLocation Loc,
4373 DeclarationName Name) {
4374 if (T.isNull() || !T->isDependentType())
4375 return T;
Mike Stump11289f42009-09-09 15:08:12 +00004376
Douglas Gregor15acfb92009-08-06 16:20:37 +00004377 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
4378 return Rebuilder.TransformType(T);
Benjamin Kramer854d7de2009-08-11 22:33:06 +00004379}
Douglas Gregorbe999392009-09-15 16:23:51 +00004380
4381/// \brief Produces a formatted string that describes the binding of
4382/// template parameters to template arguments.
4383std::string
4384Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
4385 const TemplateArgumentList &Args) {
4386 std::string Result;
4387
4388 if (!Params || Params->size() == 0)
4389 return Result;
4390
4391 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
4392 if (I == 0)
4393 Result += "[with ";
4394 else
4395 Result += ", ";
4396
4397 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
4398 Result += Id->getName();
4399 } else {
4400 Result += '$';
4401 Result += llvm::utostr(I);
4402 }
4403
4404 Result += " = ";
4405
4406 switch (Args[I].getKind()) {
4407 case TemplateArgument::Null:
4408 Result += "<no value>";
4409 break;
4410
4411 case TemplateArgument::Type: {
4412 std::string TypeStr;
4413 Args[I].getAsType().getAsStringInternal(TypeStr,
4414 Context.PrintingPolicy);
4415 Result += TypeStr;
4416 break;
4417 }
4418
4419 case TemplateArgument::Declaration: {
4420 bool Unnamed = true;
4421 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(Args[I].getAsDecl())) {
4422 if (ND->getDeclName()) {
4423 Unnamed = false;
4424 Result += ND->getNameAsString();
4425 }
4426 }
4427
4428 if (Unnamed) {
4429 Result += "<anonymous>";
4430 }
4431 break;
4432 }
4433
4434 case TemplateArgument::Integral: {
4435 Result += Args[I].getAsIntegral()->toString(10);
4436 break;
4437 }
4438
4439 case TemplateArgument::Expression: {
4440 assert(false && "No expressions in deduced template arguments!");
4441 Result += "<expression>";
4442 break;
4443 }
4444
4445 case TemplateArgument::Pack:
4446 // FIXME: Format template argument packs
4447 Result += "<template argument pack>";
4448 break;
4449 }
4450 }
4451
4452 Result += ']';
4453 return Result;
4454}